package com.heatup.apt.api.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.heatup.apt.api.controller.BaseController;
import com.heatup.apt.api.controller.pay.TenWeChatGenerator;
import com.heatup.apt.api.service.AccessService;
import com.heatup.apt.api.service.CoachPrivateSortService;
import com.heatup.apt.api.service.DataDictService;
import com.heatup.apt.api.service.OrderService;
import com.heatup.apt.api.service.TemplateSendService;
import com.heatup.apt.api.service.UserService;
import com.heatup.apt.api.service.WeChatPayService;
import com.heatup.apt.common.constants.CouponConstants;
import com.heatup.apt.common.constants.CourseConstants;
import com.heatup.apt.common.constants.DataDictConstants;
import com.heatup.apt.common.constants.ErrorCodeConstants;
import com.heatup.apt.common.constants.OrderContants;
import com.heatup.apt.common.constants.OrderContants.OrderType;
import com.heatup.apt.common.constants.ServiceConstans;
import com.heatup.apt.common.constants.UserConstants;
import com.heatup.apt.common.constants.UserProductServiceConstants;
import com.heatup.apt.common.dao.CityDiscountMapper;
import com.heatup.apt.common.dao.CompanyInfoMapper;
import com.heatup.apt.common.dao.CompanyStaffConsumeMapper;
import com.heatup.apt.common.dao.CompanyStaffMapper;
import com.heatup.apt.common.dao.CouponApiResultMapper;
import com.heatup.apt.common.dao.CouponDetailMapper;
import com.heatup.apt.common.dao.CourseInfoMapper;
import com.heatup.apt.common.dao.CourseScheduleMapper;
import com.heatup.apt.common.dao.DataDictMapper;
import com.heatup.apt.common.dao.DoorAccessPwdMapper;
import com.heatup.apt.common.dao.OrderDetailMapper;
import com.heatup.apt.common.dao.OrderInfoMapper;
import com.heatup.apt.common.dao.OrderInfoResultMapper;
import com.heatup.apt.common.dao.ProductServiceDetailMapper;
import com.heatup.apt.common.dao.ProductServiceMapper;
import com.heatup.apt.common.dao.RechargeDiscountMapper;
import com.heatup.apt.common.dao.ServicePriceMapper;
import com.heatup.apt.common.dao.SysUserMapper;
import com.heatup.apt.common.dao.VipPurchaseLogMapper;
import com.heatup.apt.common.dao.coach.CoachInfoMapper;
import com.heatup.apt.common.dao.store.StoreCoachMapper;
import com.heatup.apt.common.dao.user.UserAccountConsumeMapper;
import com.heatup.apt.common.dao.user.UserAccountRechargeMapper;
import com.heatup.apt.common.dao.user.UserDiscountMapper;
import com.heatup.apt.common.dao.user.UserInfoMapper;
import com.heatup.apt.common.dao.user.UserMealCouponMapper;
import com.heatup.apt.common.dao.user.UserProductServiceMapper;
import com.heatup.apt.common.exception.OrderException;
import com.heatup.apt.common.util.DateUtil;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.common.util.OrderUtil;
import com.heatup.apt.common.util.SmsUtil;
import com.heatup.apt.common.util.StringUtil;
import com.heatup.apt.model.CityDiscount;
import com.heatup.apt.model.DataDict;
import com.heatup.apt.model.DoorAccessPwd;
import com.heatup.apt.model.RechargeDiscount;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.api.OrderBookTypeModel;
import com.heatup.apt.model.api.OrderInfoResultModel;
import com.heatup.apt.model.api.coupon.CouponApiResultModel;
import com.heatup.apt.model.coach.CoachInfo;
import com.heatup.apt.model.company.CompanyInfo;
import com.heatup.apt.model.company.CompanyStaff;
import com.heatup.apt.model.company.CompanyStaffConsume;
import com.heatup.apt.model.coupon.CouponDetail;
import com.heatup.apt.model.course.CourseInfo;
import com.heatup.apt.model.course.CourseSchedule;
import com.heatup.apt.model.management.SysUser;
import com.heatup.apt.model.order.OrderDetail;
import com.heatup.apt.model.order.OrderInfo;
import com.heatup.apt.model.order.VipPurchaseLog;
import com.heatup.apt.model.product.ProductService;
import com.heatup.apt.model.product.ProductServiceDetail;
import com.heatup.apt.model.product.ServicePrice;
import com.heatup.apt.model.store.StoreCoach;
import com.heatup.apt.model.user.UserAccountConsume;
import com.heatup.apt.model.user.UserAccountRecharge;
import com.heatup.apt.model.user.UserDiscount;
import com.heatup.apt.model.user.UserInfo;
import com.heatup.apt.model.user.UserMealCoupon;
import com.heatup.apt.model.user.UserProductService;

@Service("weChatPayService")
public class WeChatPayServiceImpl extends BaseController implements WeChatPayService {

    private Logger logger = LoggerFactory.getLogger(WeChatPayServiceImpl.class);

    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private ServicePriceMapper servicePriceMapper;
    @Resource
    private VipPurchaseLogMapper vipPurchaseLogMapper;
    @Resource
    private UserService userService;
    @Resource
    private TemplateSendService templateSendService;
    @Resource
    private UserDiscountMapper userDiscountMapper;
    @Resource
    private OrderInfoResultMapper orderInfoResultMapper;
    @Resource
    private CourseInfoMapper courseInfoMapper;
    @Autowired
    private DataDictService dataDictService;
    @Autowired
    private CityDiscountMapper cityDiscountMapper;
    @Autowired
    private DoorAccessPwdMapper doorAccessPwdMapper;
    @Autowired
    private CourseScheduleMapper courseScheduleMapper;
    @Autowired
    private CouponApiResultMapper couponApiResultMapper;
    @Autowired
    private CouponDetailMapper couponDetailMapper;
    @Autowired
    private RechargeDiscountMapper rechargeDiscountMapper;
    @Autowired
    private UserAccountRechargeMapper userAccountRechargeMapper;
    @Autowired
    private UserAccountConsumeMapper userAccountConsumeMapper;
    @Autowired
    private CompanyStaffMapper companyStaffMapper;
    @Autowired
    private CompanyStaffConsumeMapper companyStaffConsumeMapper;
    @Autowired
    private CompanyInfoMapper companyInfoMapper;
    @Autowired
    private DataDictMapper dataDictMapper;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private ProductServiceDetailMapper productServiceDetailMapper;
    @Autowired
    private UserProductServiceMapper userProductServiceMapper;
    @Autowired
    private ProductServiceMapper productServiceMapper;
    
    @Autowired
    private CoachInfoMapper coachInfoMapper;
    
    @Autowired
    private CoachPrivateSortService coachPrivateSortService;
    @Autowired
    private StoreCoachMapper storeCoachMapper;
    
    @Autowired
    private AccessService accessService;
    
    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Autowired
    private UserMealCouponMapper userMealCouponMapper;
     
    /**
     * 修改优惠券 状态
     * @param couponDetailId
     */
    private void updateCouponDetailStatus(long couponDetailId) {

        if (couponDetailId > 0) {
            //更新优惠券使用情况. 如果是0元订单，并且是用了优惠券，则更新优惠券的状态
            CouponDetail cd = new CouponDetail();
            cd.setId(couponDetailId);
            cd.setIsUsed(1);
            cd.setUseTime(new Date());
            couponDetailMapper.updateByPrimaryKeySelective(cd);
        }
    }

    /**
     * 修改订单付款状态为付款中
     * <P>Author : fangxiaowen </P>
     * <P>Date : 2016年10月24日 </P>
     *
     * @param orderId
     * @return
     * @see WeChatPayService#updatePayStatus(java.lang.String)
     */
    @Override
    public ApiResultModel updatePayStatus(String orderId) {
        ApiResultModel<Map<Object, Object>> apiResultModel = new ApiResultModel<Map<Object, Object>>();
        Map<Object, Object> map = new HashMap<>();
        if (StringUtil.isEmpty(orderId)) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("订单ID不能为空！");
            return apiResultModel;
        }
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (null == orderInfo) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("订单信息不存在！");
            return apiResultModel;
        }
        orderInfoMapper.updateOrderPayStatus(Integer.valueOf(orderId));
        int bool = userService.isSubScribe(String.valueOf(this.getUserInfo().getId()));
        map.put("isSubScribe", bool);
        apiResultModel.setData(map);
        apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
        return apiResultModel;
    }


    private OrderInfo createOrderInfo(String orderType, String tradeNo, Date date, Integer userId,
                                      String serviceId, BigDecimal pay_amout, String tradeId, String userPwd, Integer pwdStuatus,
                                      BigDecimal primePrice, Double d_pay_amout, Double discount, int storeId, 
                                      CouponApiResultModel couponApiResultModel, Integer payType, 
                                      Long companyStaffId,String weixinAmt,String consumeAmt,String priceTypeCode, String companyAmt) throws Exception {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderStatus(OrderContants.OrderStatus.NORMAL.getStatus());
        orderInfo.setOrderSource(OrderContants.ORDER_SOURCE_WECHAT);
        orderInfo.setOrderType(Integer.valueOf(orderType));
        orderInfo.setOrderNumber(tradeNo);
        orderInfo.setVersion(0);
        orderInfo.setPayStatus(OrderContants.PayStatus.UNPAID);
        orderInfo.setCreatedTime(date);
        orderInfo.setUserId(userId);
        orderInfo.setServiceId(Integer.valueOf(serviceId));
        orderInfo.setAmount(BigDecimal.valueOf(d_pay_amout));
        orderInfo.setTradeId(tradeId);
        orderInfo.setUserPwd(userPwd);
        orderInfo.setUserPwdStatus(pwdStuatus);
        orderInfo.setPrimePrice(primePrice);
        orderInfo.setDiscount(discount);
        orderInfo.setPayType(payType);
        orderInfo.setCompanyStaffId(companyStaffId);
        if(!StringUtil.isEmpty(weixinAmt)){
        	orderInfo.setWeixinAmt(new BigDecimal(weixinAmt));
        }
        if(!StringUtil.isEmpty(consumeAmt)){
        	orderInfo.setConsumeAmt(new BigDecimal(consumeAmt));
        }
        if(!StringUtil.isEmpty(companyAmt)){
        	orderInfo.setCompanyAmt(new BigDecimal(companyAmt));
        }
        orderInfo.setPriceTypeCode(priceTypeCode);
        
        //设置订单使用的优惠券ID
        if (couponApiResultModel != null) {
            orderInfo.setCouponDetailId(couponApiResultModel.getId());
        }
        //如果订单金额为0 付款时间直接更新，付款状态为已付款
        if (d_pay_amout < 0.00001) {
            //不可退款
            Integer cancel_backmoney = 0;
            orderInfo.setCancelBackmoney(cancel_backmoney);
        }
        int orderId = orderInfoMapper.insertSelective(orderInfo);
        if (orderId < 1) {
            throw new OrderException("创建订单失败!");
        } else {
        }
        return orderInfo;
    }
    
    /**
     * 创建订单详情
     * @param orderInfo			订单信息</br>
     * @param courseCount		课程数量</br>
     * @param duration			时长</br>
     * @param personCount		人数</br>
     * @param startTime			开始时间</br>
     * @param storeId			门店Id</br>
     * @param version			版本号</br>
     * @param courseAttr		课程属性</br>
     * @param coachId			教练ID</br>
     * @param mealCount			餐的数量</br>
     * @param mealCouponCount	餐券的数量</br>
     * @param sendType			发送类型</br>
     * @param endTime			结束时间</br>
     * @param cashierId			收营员</br>
     * @throws Exception
     */
	private void createOrderDetail(OrderInfo orderInfo, int courseCount, int duration, String personCount,
			String startTime, Integer storeId, Integer version, String courseAttr, Integer coachId, Integer mealCount,
			Integer mealCouponCount, Integer sendType, String endTime, Integer cashierId) throws Exception {
		OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(Integer.valueOf(orderInfo.getId()));
        orderDetail.setServiceId(orderInfo.getServiceId());
        orderDetail.setCourseCount(courseCount);
        orderDetail.setDuration(duration);
        orderDetail.setPersonCount(Integer.valueOf(personCount));
        if(StringUtils.isEmpty(startTime)) {
        	orderDetail.setStartTime(null);
        }else {
        	orderDetail.setStartTime(DateUtils.toDateTime(startTime));
        }
        if(StringUtils.isEmpty(endTime)) {
        	orderDetail.setEndTime(null);
        }else {
        	orderDetail.setEndTime(DateUtils.toDateTime(endTime));
        }
        
        orderDetail.setStoreId(Integer.valueOf(storeId));
        orderDetail.setCourseAttr(courseAttr.replaceAll(",", "#"));
        orderDetail.setCoachId(coachId);
        orderDetail.setMealCount(mealCount);
        orderDetail.setMealCouponCount(mealCouponCount);
        orderDetail.setSendType(sendType);
        orderDetail.setCashierId(cashierId);
        final int orderDetailCount = orderDetailMapper.insert(orderDetail);
        if (orderDetailCount < 1) {
            throw new OrderException("插入订单明细失败!");
        }
    }

    /**
     * 修改订单付款状态
     * <P>Author : fangxiaowen </P>
     * <P>Date : 2016年8月26日 </P>
     *
     * @param orderNumber
     * @param tradeNo
     * @see WeChatPayService#updatePayOrder(java.lang.String, java.lang.String)
     */
    @Override
    @Transactional
    public boolean updatePayOrder(String orderNumber, String tradeNo) {
        logger.info("==============WeChatPayServiceImpl updatePayOrder start==============");
        logger.info("updatePayOrder method params is " + " orderId:" + orderNumber + " tradeNo:" + tradeNo);

        String orderStatus = OrderContants.OrderStatus.NORMAL.getStatus();//初始化是给正常状态

        OrderInfoResultModel orderInfoResultModel = orderInfoResultMapper.selectByOrderNumber(orderNumber);

        if (OrderContants.PayStatus.PAID.equals(orderInfoResultModel.getPayStatus())) {
            //微信可能会多次回调，每次回调已置为已付款，每次查询已付款，则跳出即可
            logger.info("==============WeChatPayServiceImpl updatePayOrder OrderContants.PayStatus.PAID==============");
            return false;
        }
        
        
        if (orderInfoResultModel != null
                && orderInfoResultModel.getOrderType() != OrderContants.OrderType.vip_order.getIndex()
                && orderInfoResultModel.getOrderType() != OrderContants.OrderType.user_account.getIndex()
                && orderInfoResultModel.getOrderType() != OrderContants.OrderType.monthly_card.getIndex()
                && orderInfoResultModel.getOrderType() != OrderContants.OrderType.physical_examination.getIndex()
        		&& orderInfoResultModel.getOrderType() != OrderContants.OrderType.secret_experience.getIndex()
				&& orderInfoResultModel.getOrderType() != OrderContants.OrderType.private_bespeak.getIndex()
				&& orderInfoResultModel.getOrderType() != OrderContants.OrderType.meal.getIndex()
        		) {
            OrderDetail orderDetail = orderInfoResultModel.getOrderDetail();
            ServicePrice servicePrice = orderInfoResultModel.getServicePrice();
            UserDiscount userDiscount = servicePriceMapper.getUserDiscountById(orderInfoResultModel.getServiceId());

            // 团课订单
            if (StringUtil.isEquals(orderInfoResultModel.getOrderType(),
                    OrderContants.OrderType.team_course.getType())) {
                CourseInfo courseInfo = courseInfoMapper.selectById(servicePrice.getCourseId());
                // 最大人数
                int maxCount = courseInfo.getMaxCount();
                int currentCount = courseInfo.getCurrentCount() == null ? 0 : courseInfo.getCurrentCount();
                int waitCount = courseInfo.getWaitCount() == null ? 0 : courseInfo.getWaitCount();
                // 当前人数小于最大人数，则订单为正常状态，否则需要排队
                if (currentCount < maxCount) {
                    //正常订单
                    //orderStatus= OrderContants.OrderStatus.NORMAL.getStatus();
                    currentCount += orderDetail.getPersonCount();
                    courseInfo.setCurrentCount(currentCount);
                } else {
                    //log.info("排队订单");
                    orderStatus = OrderContants.OrderStatus.WAIT.getStatus();
                    waitCount += orderDetail.getPersonCount();
                    courseInfo.setWaitCount(waitCount);
                    // 获取最大排队人数
                    int wait = orderInfoMapper.queryMaxWaitNumber(orderInfoResultModel.getServiceId());
                    wait = wait + 1;
                    orderDetail.setWaitNumber(wait);
                }
                // 更新订单课程信息
                courseInfoMapper.updateSelectiveById(courseInfo);
                orderDetailMapper.updateSelectiveById(orderDetail);
                
                
            }else if (StringUtil.isEquals(orderInfoResultModel.getOrderType(), OrderContants.OrderType.fun_camp.getType())) {
            	 	// 檬营订单
	                if (servicePrice.getCourseId() != null) {
	                    CourseInfo courseInfo = courseInfoMapper.queryCampCourseById(servicePrice.getCourseId());
	                    int waitCount = courseInfo.getWaitCount() == null ? 0 : courseInfo.getWaitCount();
	                    int maxCount = courseInfo.getMaxCount();
	                    int currentCount = courseInfo.getCurrentCount() == null ? 0 : courseInfo.getCurrentCount();
	
	                    if (currentCount < maxCount) {
	                        // 正常订单
	                        //orderStatus=OrderContants.OrderStatus.NORMAL.getStatus();
	                        currentCount += orderDetail.getPersonCount();
	                        courseInfo.setCurrentCount(currentCount);
	                    } else if (courseInfo.getDeadline() != null
	                            && (new Date()).compareTo(courseInfo.getDeadline()) < 0) {
	                        // 排队订单 (当前未到截止日期)
	                        logger.info("檬营排队订单===付款确认===================>>>>");
	                        
	                        orderStatus = OrderContants.OrderStatus.WAIT.getStatus();
	                        waitCount += orderDetail.getPersonCount();
	                        courseInfo.setWaitCount(waitCount);
	                        courseInfo.setCurrentCount(currentCount);
	                        // 获取最大排队人数
	                        int wait = orderInfoMapper.queryMaxWaitNumber(orderInfoResultModel.getServiceId());
	                        logger.info("檬营排队订单===付款确认=获取最大排队人数=======wait=====>>>>" + wait);
	                        orderDetail.setWaitNumber(++wait);
	                    }
	                    // 更新订单课程信息
	                    courseInfoMapper.updateSelectiveById(courseInfo);
	                    orderDetailMapper.updateSelectiveById(orderDetail);
	                    logger.info("檬营排队订单===付款确认=====更新订单课程信息完成======>>>>");
	                    logger.info("檬营排队订单===付款确认=====更新订单课程信息 orderStatus======>>>>" + orderStatus);
	                    
	                }
            }else if (StringUtil.isEquals(orderInfoResultModel.getOrderType(), OrderContants.OrderType.pt.getType())) {
	            	// 私教
	                CourseInfo courseInfo = courseInfoMapper.selectById(servicePrice.getCourseId());
	                int currentCount = courseInfo.getCurrentCount() + orderInfoResultModel.getOrderDetail().getPersonCount();
	                logger.info("========私教课程更新人数======================currentCount:" + currentCount);
	                courseInfo.setCurrentCount(currentCount);
	                // 添加餐券数量
	                addUserMealCoupon(orderInfoResultModel);
	                // 更新订单课程信息
	                courseInfoMapper.updateSelectiveById(courseInfo);
	                // 包含年卡的私教
	                if(courseInfo.getProductServiceDetailId() != null && courseInfo.getProductServiceDetailId() > 0) {
	                	OrderInfo orderInfo = orderInfoResultModel;
	                	orderInfo.setServiceId(courseInfo.getProductServiceDetailId());
	                	orderInfoResultModel.setServiceId(courseInfo.getProductServiceDetailId());
	                	createMonthlyCardPurchaseLog(orderInfo, orderInfoResultModel, false);
	                }
                    templateSendService.sendBookSuccOrderForCoach(orderInfoResultModel.getId());
                    
            }
            

            //排队订单发送排队模版消息
            if (orderStatus.equals(OrderContants.OrderStatus.WAIT.getStatus())) {
                templateSendService.sendOrderWaitTemplateMsg(orderInfoResultModel);
            } else {
                templateSendService.sendBookingSuccTemplateMsg(orderInfoResultModel.getId(), orderStatus);
            }
            
            //会员订单
        } else if (orderInfoResultModel != null 
        		&& (orderInfoResultModel.getOrderType() == OrderContants.OrderType.vip_order.getIndex() || orderInfoResultModel.getOrderType() ==OrderContants.OrderType.monthly_card.getIndex())) {
//        	createVipPurchaseLog(orderNumber,orderInfoResultModel);
        	
        	createVipPurchaseLogRestructure(orderNumber, orderInfoResultModel);
        	
        }
        // 充值虚拟账户
        else if (orderInfoResultModel != null 
        		&& StringUtil.isEquals(orderInfoResultModel.getOrderType(), OrderContants.OrderType.user_account.getType())) {
            logger.info("=========== update user by userAccount start ===================================");
            int userId = orderInfoResultModel.getUserId();
            int serviceId = orderInfoResultModel.getServiceId();

            UserInfo userInfo = userInfoMapper.selectById(userId);
            BigDecimal amount_all = userInfo.getAccountAmt();
            // 1 先根据serviceId查询对应的面额和实到金额
            RechargeDiscount rechargeDiscount = null;
            rechargeDiscount = rechargeDiscountMapper.selectById(serviceId);
            // 先判断用户的用户等级
            if (userInfo.getLevel() == UserConstants.UserLevel.user.getIndex()) {
                amount_all = amount_all.add(rechargeDiscount.getUserActualAmt());
            } else {
                amount_all = amount_all.add(rechargeDiscount.getVipActualAmt());
            }
            userInfo.setAccountAmt(amount_all);
            int bool = userInfoMapper.updateSelectiveById(userInfo);
            // 用户充值记录插入
            UserAccountRecharge uar = insetUserAccountRecharge(userInfo, String.valueOf(serviceId), orderInfoResultModel.getOrderNumber());
            logger.info("===========params：userId" + userId + " serviceId:" + serviceId + "userAccount:" + amount_all + "==bool：" + bool + "=====================");
            templateSendService.sendCashCardRechargeSucc(uar);
            
        }else if(orderInfoResultModel.getOrderType() == OrderContants.OrderType.physical_examination.getIndex()
        		|| orderInfoResultModel.getOrderType() == OrderContants.OrderType.secret_experience.getIndex()){
        	// 体测订单|| 私教体验订单
        	assignTasksToCoach(orderInfoResultModel);
        	templateSendService.sendBookingSuccTemplateMsg(orderInfoResultModel.getId(), orderStatus);
        	templateSendService.sendBookSuccOrderForCoach(orderInfoResultModel.getId());
        	
        }else if(orderInfoResultModel.getOrderType() == OrderContants.OrderType.private_bespeak.getIndex()){
        	/*Integer storeId = storeCoachMapper.queryStoreIdByCoachId(orderInfoResultModel.getOrderDetail().getCoachId());
        	OrderDetail orderDetail = orderInfoResultModel.getOrderDetail();
        	if(orderDetail != null && orderDetail.getStoreId() == 0){
        		orderDetail.setStoreId(storeId);
        		orderDetailMapper.updateSelectiveById(orderDetail);
        	}*/
//        	sendShortMessage(orderInfoResultModel.getUserInfo(),orderInfoResultModel.getOrderType(),orderInfoResultModel.getOrderDetail().getCourseAttr(),orderInfoResultModel.getOrderDetail().getCoachId());
            templateSendService.sendBookSuccOrderForCoach(orderInfoResultModel.getId());
            
        }else if(orderInfoResultModel.getOrderType() == OrderContants.OrderType.meal.getIndex()) { // 线下购餐 
        	
        	// 线下购餐
        	UserInfo userInfo = userInfoMapper.selectById(orderInfoResultModel.getUserId());
        	logger.info("======update user AccountAmt :"+userInfo.getAccountAmt() +"======pay ConsumeAmt"+orderInfoResultModel.getConsumeAmt());
        	userInfo.setAccountAmt(userInfo.getAccountAmt().subtract(orderInfoResultModel.getConsumeAmt()));
        	int bool = userInfoMapper.updateSelectiveById(userInfo);
        	// 发送模板消息
        	templateSendService.sendPayMealOrderMsg(orderInfoResultModel, userInfo);
        	
        }
        // 微信加储值卡混合支付
        if(orderInfoResultModel.getPayType().intValue() == OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT){
        	UserInfo userInfo = userInfoMapper.selectById(orderInfoResultModel.getUserId());
        	logger.info("======update user AccountAmt :"+userInfo.getAccountAmt() +"======pay ConsumeAmt"+orderInfoResultModel.getConsumeAmt());
        	userInfo.setAccountAmt(userInfo.getAccountAmt().subtract(orderInfoResultModel.getConsumeAmt()));
        	int bool = userInfoMapper.updateSelectiveById(userInfo);
        	logger.info(" update userInfo bool:"+bool);
        	
        }else if(orderInfoResultModel.getPayType().intValue() == OrderContants.PAY_TYPE_COMPANY_WECHAT_ACCOUNT){
        	
        	insertCompanyStaffConsume(orderInfoResultModel.getId(), new Date(), orderInfoResultModel.getOrderStatus(), orderInfoResultModel.getCompanyAmt().toString(), orderInfoResultModel.getUserInfo(), orderInfoResultModel.getCompanyStaffId());
        
        }
        // 如果有优惠券，则把该优惠券置为已使用
        if (orderInfoResultModel != null && orderInfoResultModel.getCouponDetailId() != null
                && orderInfoResultModel.getCouponDetailId() > 0) {
            updateCouponDetailStatus(orderInfoResultModel.getCouponDetailId());
            
        }
        
        Map<Object, Object> map = new HashMap<Object, Object>();
        map.put("payStatus", OrderContants.PayStatus.PAID);
        map.put("orderNumber", orderNumber);
        map.put("tradeNo", tradeNo);
        map.put("orderStatus", orderStatus);
        map.put("version", orderInfoResultModel.getVersion());

        int result = orderInfoMapper.updatePayOrder(map);
        logger.info("=====> update Pay Order finish================" + map);
        return result > 0;
    }

    @Override
    public UserDiscount getUserDiscount(int id) {
        //UserDiscount ud = userDiscountMapper.getUserDiscountById(1);
    	UserDiscount ud = userDiscountMapper.selectById(id);
        return ud;
    }

    /**
     * 获取有效的交易编号
     *
     * @return
     */
    public String getTradeId() {
        Date nowDate = new Date();
        String tradeId = DateUtils.format(nowDate, DateUtils.datePatternAllSimple);
        while (true) {
            int num = (int) (Math.random() * 9000 + 1000);
            tradeId = tradeId + num;
            int bool = orderInfoMapper.checkTradeIdIsOK(tradeId);
            if (bool == 0)
                break;
        }
        return tradeId;
    }

    /**
     * 校验密码的有效性能 有缺陷
     *
     * @return
     */
    public String getUserPwd(int storeId) {
    	// 新方法
        return accessService.returnNewRandomPassword();
    }

    /**
     * 计算金额: amount * count * discount = orderAmount 在
     * 四舍五入
     *
     * @param amount   原价
     * @param count    购买数量
     * @param discount 折扣
     * @return
     */
    private BigDecimal reckonOrderAmount(BigDecimal amount, String count, double discount) {
        BigDecimal orderAmount = null;
        double count_num = Double.parseDouble(count);
        orderAmount = amount.multiply(BigDecimal.valueOf(count_num));
        orderAmount = orderAmount.multiply(BigDecimal.valueOf(discount));
        return orderAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 根据订单类型和服务id去查询价格
     *
     * @param orderType
     * @param serviceId
     * @param
     * @param duration
     * @return
     */
    private BigDecimal getOrderAmount(String orderType, String serviceId, String personCount, UserInfo userInfo, String duration, CouponApiResultModel couponApiResultModel, int courseCount,Integer payType,String payAmount) {
        BigDecimal amount_all = null;

        // 查询服务价格
        ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(Integer.valueOf(serviceId));
        // 合作店可享受的权益
        int has_vip_service = 0;
        int level = userInfo.getLevel();
       
        // 处理会员订单和储值卡充值以外
        if (Integer.valueOf(orderType) != OrderContants.OrderType.vip_order.getIndex() && Integer.valueOf(orderType) != OrderContants.OrderType.user_account.getIndex()) {
            List<DataDict> dataDicts = dataDictService.queryDataDicts(DataDictConstants.DICT_TYPE_SELF_FITNESS_TIME);
            // 查询折扣
            CityDiscount cityDiscount = cityDiscountMapper.queryCityDiscountByStoreId(servicePrice.getStoreId());
            // 原价
            BigDecimal primePrice = servicePrice.getPrimePrice();
            // 团课
            if (OrderContants.OrderType.team_course.getType().equals(orderType)) {
                if (level == 2 || has_vip_service == 1) {
                    if (servicePrice.getPrice() != null) {
                        amount_all = servicePrice.getPrice().multiply(BigDecimal.valueOf(Long.valueOf(personCount)));
                    } else {
                        amount_all = primePrice.multiply(cityDiscount.getVipDiscount()).setScale(2, BigDecimal.ROUND_HALF_UP);
                        amount_all = amount_all.multiply(BigDecimal.valueOf(Long.valueOf(personCount)));
						/*amount_all = primePrice.multiply(BigDecimal.valueOf(Long.valueOf(personCount))
								.multiply(cityDiscount.getVipDiscount()));*/
                    }
                } else {
                    amount_all = primePrice.multiply(BigDecimal.valueOf(Long.valueOf(personCount)));
                }
            } else if (OrderContants.OrderType.selffit.getType().equals(orderType)) {
                DataDict dataDict = null;
                // 获取数据字典中与自助健身时长相关的系数
                for (DataDict dd : dataDicts) {
                    if (dd.getDictName().trim().equals(duration.trim())) {
                        dataDict = dd;
                        break;
                    }
                }
                BigDecimal beishu = BigDecimal.valueOf(Double.parseDouble(dataDict.getDictCode()));
                // 会员计算总金额
                if (level == 2 || has_vip_service == 1) {
                    if (servicePrice.getPrice() != null) {
                        // 有会员优惠价格时取会员优惠价*人数*时长系数
                        amount_all = servicePrice.getPrice().multiply(beishu)
                                .multiply(BigDecimal.valueOf(Long.valueOf(personCount)));
                    } else {
                        amount_all = primePrice.multiply(beishu).multiply(BigDecimal.valueOf(Long.valueOf(personCount)))
                                .multiply(cityDiscount.getVipDiscount());
                    }
                } else {
                    amount_all = servicePrice.getPrimePrice().multiply(beishu)
                            .multiply(BigDecimal.valueOf(Double.parseDouble(personCount)));
                }

            }
            //  私教按照课次来收费了
            else if (OrderContants.OrderType.pt.getType().equals(orderType)) {
                BigDecimal courseNum = new BigDecimal(courseCount);
                if (level == 2 || has_vip_service == 1) {
                    amount_all = servicePrice.getPrice().multiply(courseNum);
					/*amount_all = amount_all.multiply(BigDecimal.valueOf(Double.parseDouble(personCount)));*/
                } else {
                    amount_all = servicePrice.getPrimePrice().multiply(courseNum);
                }
                amount_all = amount_all.multiply(BigDecimal.valueOf(Double.parseDouble(personCount)));
            } else {
                if (level == 2 || has_vip_service == 1) {

                    BigDecimal amount_cd = null;//servicePrice.getPrice();
                    if (servicePrice.getPrice() != null) {
                        amount_cd = servicePrice.getPrice();
                    } else {
                        amount_cd = servicePrice.getPrimePrice().multiply(cityDiscount.getVipDiscount());
                    }

                    amount_all = amount_cd.setScale(2, BigDecimal.ROUND_HALF_UP);
                    amount_all = amount_all.multiply(BigDecimal.valueOf(Long.valueOf(personCount)));
                } else {
                    amount_all = primePrice.multiply(BigDecimal.valueOf(Long.valueOf(personCount)));
                }
            }
        } else if (OrderContants.OrderType.vip_order.getType().equals(orderType)) {
            //购买会员订单
            UserDiscount userDiscount = servicePriceMapper.getUserDiscountById(Integer.valueOf(serviceId));
            amount_all = userDiscount.getPrimePrice().multiply(BigDecimal.valueOf(userDiscount.getDiscount()));
        } else if (OrderContants.OrderType.user_account.getType().equals(orderType)) {// 用户虚拟账户充值
            // 1 先根据serviceId查询对应的面额和实到金额
            RechargeDiscount rechargeDiscount = null;
            rechargeDiscount = rechargeDiscountMapper.selectById(Integer.valueOf(serviceId));
            amount_all = rechargeDiscount.getFaceAmt();
        } else {
            amount_all = BigDecimal.valueOf(-1);
        }

        //添加优惠券金额校验
        if (couponApiResultModel != null) {
            amount_all = this.getCouponAmountAll(couponApiResultModel, amount_all);
        }

        return amount_all.setScale(2, BigDecimal.ROUND_HALF_UP);
    }


    //根据优惠券类型类返回具体金额的值
    private BigDecimal getCouponAmountAll(CouponApiResultModel couponApiResultModel, BigDecimal amount_all) {
        if (couponApiResultModel != null) {
            if (CouponConstants.CouponType_Money.equals(couponApiResultModel.getCoupon_type())) {
                //现金券
                BigDecimal ret = amount_all.subtract(couponApiResultModel.getCash_money());
                if (ret.compareTo(BigDecimal.ZERO) == -1)  //订单金额12元，但用了一张20元的券，不能返回负数
                    return BigDecimal.valueOf(0);
                else
                    return ret;
            } else if (CouponConstants.CouponType_Discount.equals(couponApiResultModel.getCoupon_type())) {
                //折扣券
                return amount_all.multiply(couponApiResultModel.getDiscount());
            } else if(CouponConstants.CouponType_Course.equals(couponApiResultModel.getCoupon_type())){
            	//课程体验券
            	return BigDecimal.valueOf(0);
            }else
            {
                return BigDecimal.valueOf(-1);
            }
        } else {
            return BigDecimal.valueOf(-1);
        }
    }


    /**
     * 创建进店密码
     *
     * @param orderId
     * @param storeId
     * @param orderType
     * @param startTime
     * @param duration
     * @param passwork
     * @param serviceId
     * @return
     */
    public int createStorePwdByOrderId(int orderId, int storeId, String orderType, String startTime, Integer duration, String passwork, String serviceId) {
        logger.info("=================================created store password by orderId:" + orderId + "  statr");
        Date end_time = null;
        Date start_time = null;
        // 团课订单
        if ("1".equals(orderType)) {
            ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(Integer.valueOf(serviceId));
            CourseSchedule courseSchedule = courseScheduleMapper.selectByCourseId(servicePrice.getCourseId());
            end_time = courseSchedule.getEndTime();
            start_time = courseSchedule.getStartTime();
        } else if ("4".equals(orderType)) {
            try {
                end_time = DateUtils.addMinutes(DateUtils.toDateTime(startTime), duration);
                start_time = DateUtils.toDateTime(startTime);
            } catch (NumberFormatException | ParseException e) {
                logger.info("=================================创建门店密码的时候 时间转换出现类型不匹配导致创建失败========================");
                e.printStackTrace();
            }
        }else{
        	logger.info("=================================私教 檬营 会员 个人储值卡充值等订单在创建订单的时候不创建进店密码 ====================================");
            return 1;
        }
        DoorAccessPwd dAccessPwd = new DoorAccessPwd();
        dAccessPwd.setRelationId(orderId);
        dAccessPwd.setRelationType(0);
        dAccessPwd.setStoreId(storeId);
        dAccessPwd.setPassword(passwork);
        dAccessPwd.setPwdStatus("0");
        dAccessPwd.setStartTime(start_time);
        dAccessPwd.setEndTime(end_time);
        dAccessPwd.setCreatedTime(new Date());
        dAccessPwd.setUpdatedTime(new Date());
        dAccessPwd.setRemark("创建订单");
        int bool = doorAccessPwdMapper.createdDoorAccessPwd(dAccessPwd);
        logger.info("=================================created store password by orderId end status bool:" + bool);
        return bool;
    }

    /**
     * 插入充值记录信息
     *
     * @param userInfo
     * @param serviceId
     * @param userInfo
     * @param orderId
     * @return
     */
    public UserAccountRecharge insetUserAccountRecharge(UserInfo userInfo, String serviceId, String orderId) {
        logger.info("============= insert userAccountRecharge  by wechat pay start ======================");
        logger.info("=============params: userName" + userInfo.getUserName() + " serviceId" + serviceId + " orderId " + orderId + "======================");
        UserAccountRecharge userAccountRecharge = new UserAccountRecharge();
        // 1 先根据serviceId查询对应的面额和实到金额
        RechargeDiscount rechargeDiscount = null;
        rechargeDiscount = rechargeDiscountMapper.selectById(Integer.valueOf(serviceId));
        BigDecimal amount_all = null;
        if (userInfo.getLevel() == UserConstants.UserLevel.user.getIndex()) {
            amount_all = rechargeDiscount.getUserActualAmt();
        } else {
            amount_all = rechargeDiscount.getVipActualAmt();
        }
        rechargeDiscount.getFaceAmt();
        userAccountRecharge.setUserId(userInfo.getId());
        userAccountRecharge.setFaceAmt(rechargeDiscount.getFaceAmt());
        userAccountRecharge.setActualAmt(amount_all);
        userAccountRecharge.setRechargeType(1);
        userAccountRecharge.setCreateTime(new Date());
        userAccountRecharge.setRemark("微信支付");
        userAccountRecharge.setChangeCode(orderId);
        int bool = userAccountRechargeMapper.insertSelective(userAccountRecharge);
        logger.info("=============FaceAmt:" + rechargeDiscount.getFaceAmt() + " ActualAmt:" + amount_all + "======================");
        logger.info("============= insert userAccountRecharge  by wechat pay end ======================");
        return userAccountRecharge;
    }

    /**
     * 插入消费记录
     *
     * @param userInfo
     * @param orderNumber
     */
    public void insertUserAccountConsume(UserInfo userInfo, String orderNumber) {
        logger.info("============insert UserAccountConsume start =====================");
        UserAccountConsume userAccountConsume = new UserAccountConsume();
        OrderInfoResultModel orderInfoResultModel = orderInfoResultMapper.selectByOrderNumber(orderNumber);
        BigDecimal consumeAmt = orderInfoResultModel.getPayType() == OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT ? orderInfoResultModel.getConsumeAmt() : orderInfoResultModel.getAmount();
        String consumeType = "1";// orderInfoResultModel.getOrderType() == 5 ? "2" : "1"
        if(orderInfoResultModel.getOrderType().intValue() == OrderContants.OrderType.vip_order.getIndex()
        		|| orderInfoResultModel.getOrderType().intValue() == OrderContants.OrderType.monthly_card.getIndex())
        {
        	consumeType = "2";
        }
        userAccountConsume.setUserId(userInfo.getId());
        userAccountConsume.setConsumeAmt(consumeAmt);
        userAccountConsume.setConsumeType(consumeType);
        //修改消费类型，根据订单来消费
        userAccountConsume.setRemark(OrderContants.OrderType.getOrderType(orderInfoResultModel.getOrderType().toString()).getTitle());
        userAccountConsume.setCreateTime(new Date());
        userAccountConsume.setOrderId(orderInfoResultModel.getId());
        int bool = userAccountConsumeMapper.insertSelective(userAccountConsume);
        logger.info("============insert UserAccountConsume end bool:" + bool + "=====================");

    }
    
    /**
     * 判断当前企业员工是否符合使用vip权益</br>
     * 主要用途是用于给予加盟店中该店的会员所能享受的权益</br>
     * @param servicePrice
     * @param userInfo
     * @return
     */
    public int has_vip_company(ServicePrice servicePrice,UserInfo userInfo,String orderType,int personCount,String payAmount){
    	logger.info("===========================has_vip_company start =====================");
    	 int has_vip_service = 0;
    	 CompanyStaff companyStaff = companyStaffMapper.selectCompanyPaymentDetailByUserId(userInfo.getId());
         if(companyStaff != null){
         	CompanyInfo companyInfo = companyInfoMapper.selectById(companyStaff.getCompanyId());
         	// 1 判断结算类型是否是需要按照会员价来计算
         	int vipCheckType = companyInfo.getVipCheckType();
         	if(vipCheckType == 1){// 按照原价来计算不做一下校验处理
         		return 0;
         	}else{// 按照会员计算给予权益
         		int storeId = servicePrice.getStoreId();
             	int serviceType = servicePrice.getServiceType();
             	int has_course_service = 0 ;
             	//服务类型(1团课订单 2私教订单 3檬营订单 4自助健身 5会员)
             	logger.info("===========================getOrderAmount: order serviceType:"+serviceType+"=====================");
             	// 2 判断一下订单类型该企业员工是否享有课程折扣
             	if(serviceType == 1){
             		has_course_service = companyInfo.getVipCheckCourseTypeTeam();
             	}else if(serviceType == 2){
             		has_course_service = companyInfo.getVipCheckCourseTypePrivate();
             	}else if(serviceType == 3){
             		has_course_service = companyInfo.getVipCheckCourseTypeCamp();
             	}else if(serviceType == 4){
             		has_course_service = companyInfo.getVipCheckCourseTypeSelf();
             	}
             	if(companyInfo != null){
             		String stores = companyInfo.getVipCheckStoreList();
             		// 3 先是判断当前企业是否限制了使用门店
             		if(companyInfo.getVipCheckStoreLimit() ==1){// 不限制
             			if(has_course_service == 1){
             				has_vip_service = 1 ;
             			}
             		}else{// 限制门店
             			if(!StringUtil.isEmpty(stores)){
                 			String[] storList = stores.split("#");
                 			for(String s:storList){// 判断当前门店是否在可使用门店里面
                 				if(storeId == Integer.valueOf(s)  && has_course_service == 1){
                 					has_vip_service = 1 ;
                 					break;
                 				}
                 			}
                 		}
             		}
             		
             	}
             }
         	}
         if(has_vip_service == 1){
        	 Map<String,Object> mapCheck = checkCompanyPayOrderNew(userInfo, servicePrice, Integer.valueOf(orderType), Integer.valueOf(personCount), payAmount,null);
             if(!(boolean) mapCheck.get("isPay")){
            	 has_vip_service = 0;
             }
         }
    	return has_vip_service;
    }
    
    /**
     * 企业储值卡订单校验
     * 这里只是校验课程订单 团课 私教 檬营 自助健身
     * @param userInfo
     * @param servicePrice
     * @param orderType
     * @param personCount
     * @param payAmount
     * @return
     */
    public Map<String,Object> checkCompanyPayOrderNew(UserInfo userInfo,ServicePrice servicePrice,Integer orderType,Integer personCount,String payAmount,CouponApiResultModel couponApiResultModel){
    	CityDiscount cityDiscount = cityDiscountMapper.queryCityDiscountByStoreId(servicePrice.getStoreId());
    	Map<String,Object> map = new HashMap<String, Object>();
    	map.put("isVip", true);// 是否值vip价格购买
		map.put("isMany", true);// 是否可以购买多次
		map.put("isPay", true);// 是否可以支付
		map.put("msg", "返回信息");// 返回信息
		BigDecimal p_couponAmount = new BigDecimal(0);
    	BigDecimal p_payAmount = new BigDecimal(payAmount);// 实付总额
    	BigDecimal p_primeprice = servicePrice.getPrimePrice().multiply(new BigDecimal(personCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
    	BigDecimal p_price = 
    			servicePrice.getPrice() == null?
    					servicePrice.getPrimePrice().multiply(cityDiscount.getVipDiscount()).multiply(new BigDecimal(personCount)).setScale(2, BigDecimal.ROUND_HALF_UP)
    					:servicePrice.getPrice().multiply(new BigDecimal(personCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
		CompanyStaff companyStaff = companyStaffMapper.selectCompanyPaymentDetailByUserId(userInfo.getId());
		CompanyInfo companyInfo = null;
		if(companyStaff != null){
			companyInfo = companyInfoMapper.selectById(companyStaff.getCompanyId());
		}		

		List<OrderInfo> listO = orderInfoMapper.quertOrderListByServiceIdAndUserIdAndOrderType(servicePrice.getId(),userInfo.getId(),orderType);
		if(couponApiResultModel != null){
			p_couponAmount = couponApiResultModel.getCash_money();
			p_primeprice = p_primeprice.subtract(p_couponAmount);
			p_price = p_price.subtract(p_couponAmount);
		}
		logger.info("====================checkCompanyPayOrderNew  start :payAmount"+payAmount+" p_primeprice"+p_primeprice+" p_price:"+p_price);
		// 会员价
		if(companyInfo == null){
			map.put("isVip", (userInfo.getLevel() == UserConstants.UserLevel.vip.getIndex()?true:false));// 是否值vip价格购买
			map.put("isMany", false);// 是否可以购买多次
			map.put("isPay", true);// 是否可以支付
			map.put("msg", "不是企业员工！");// 返回信息
			logger.info("======================checkCompanyPayOrderNew:该用户不是企业员工=================== ");
			return map;
		}
		logger.info("====================checkCompanyPayOrderNew vipCheckType:"+companyInfo.getVipCheckType() +" VipCheckVipPriceOrderMany:"+companyInfo.getVipCheckVipPriceOrderMany());
		if(p_payAmount.compareTo(p_price) == 0){
			// 判断是否是可支持多次购买
			// 以原价购买 只能以会员价购买一次不能购买多次
			if(companyInfo.getVipCheckType() != 0 && Integer.valueOf(personCount) != 1){
				map.put("isVip", false);// 是否值vip价格购买
				map.put("isMany", false);// 是否可以购买多次
				map.put("isPay", false);// 是否可以支付
				map.put("msg", "实付金额不正确！");// 返回信息
				logger.info("======================checkCompanyPayOrderNew:该企业不支持会员价购买 vipchecktype "+companyInfo.getVipCheckType()+"==================== ");
				return map;
			}
			// 以原价购买 只能以会员价购买一次
			if(companyInfo.getVipCheckType() != 0 && userInfo.getLevel().intValue() == UserConstants.UserLevel.vip.getIndex()){
				map.put("isVip", true);// 是否值vip价格购买
				map.put("isMany", false);// 是否可以购买多次
				map.put("isPay", true);// 是否可以支付
				map.put("msg", "实付金额不正确！");// 返回信息
				logger.info("======================checkCompanyPayOrderNew:以原价购买 只能以会员价购买一次 vipchecktype "+companyInfo.getVipCheckType()+"==================== ");
				return map;
			}
			logger.info("==============listO.size()："+listO.size()+" =============orderType:"+orderType);
			// 不使用企业储值卡的情况下会员价只能是购买一次
			if(listO.size() > 0 && orderType != OrderContants.PAY_TYPE_COMPANY_ACCOUNT){
				map.put("isVip", false);// 是否值vip价格购买
				map.put("isMany", false);// 是否可以购买多次
				map.put("isPay", false);// 是否可以支付
				map.put("msg", "不能再次使用会员价购买！");// 返回信息
				logger.info("======================checkCompanyPayOrderNew:因为之前已经购买过了一次所有不能再次使用会员价购买了==================== ");
				return map;
			}
			
			// 支持会员价  不支持多次购买
			if(companyInfo.getVipCheckVipPriceOrderMany() != 1 && listO.size() > 0){
				map.put("isVip", false);// 是否值vip价格购买
				map.put("isMany", false);// 是否可以购买多次
				map.put("isPay", false);// 是否可以支付
				map.put("msg", "该课程您不能以会员价重复购买");// 返回信息
				logger.info("======================checkCompanyPayOrderNew:该用户之前使用过会员价购买过该课程了不能再次使用会员价购买==================== ");
				return map;
			}
			// 支持会员价 不支持一人购买多个
			if(companyInfo.getVipCheckVipPriceOrderMany() != 1 && Integer.valueOf(personCount) >1){
				map.put("isVip", false);// 是否值vip价格购买
				map.put("isMany", false);// 是否可以购买多次
				map.put("isPay", false);// 是否可以支付
				map.put("msg", "该课程您只能一人购买一次");// 返回信息
				logger.info("======================checkCompanyPayOrderNew: 该企业不支持购买多次 personCount"+personCount+"==================== ");
				return map;
			}
			
		}
		// 原价购买
		else if(p_payAmount.compareTo(p_primeprice) == 0){
			map.put("isVip", false);// 是否值vip价格购买
			map.put("isMany", true);// 是否可以购买多次
			map.put("isPay", true);// 是否可以支付
			map.put("msg", "原价随便买");// 返回信息
		}else{
			map.put("isVip", false);// 是否值vip价格购买
			map.put("isMany", false);// 是否可以购买多次
			map.put("isPay", false);// 是否可以支付
			map.put("msg", "实付金额不正确！");// 返回信息
			logger.info("======================= checkCompanyPayOrder : The amount paid is incorrect p_price:"+p_price+"  p_payAmount："+p_payAmount);
		}
		return map;
    }
    
    /**
     * 创建订单重构
     * create timo 2017-03-21
     * @param userInfo 用户信息
     * @param payAmount 实付金额
     * @param orderType 订单类型
     * @param serviceId 订单种类
     * @param personCount 购买人数
     * @param apbillCreateIp
     * @param storeId 门店
     * @param startTime 开始时间 用于 自助健身
     * @param endTime 结束时间 用于自助健身
     * @param duration 时长
     * @param courseCount 课次
     * @param couponDetailId 使用优惠券id
     * @param payType 支付类型 
     * @param weixinAmt 微信金额
     * @param consumeAmt 储值卡金额
     * @param productId 包月卡产品id add jxy 
     * @param companyAmt 企业储值卡实付金额
     * @param courseAttr 私教预约方向
     * @param coachId 教练ID
     * @return
     * @throws Exception 
     */
	public ApiResultModel createPayOrderRestructure(UserInfo userInfo, final String payAmount, final String orderType,
			final String serviceId, final String personCount, final String apbillCreateIp, Integer storeId,
			String startTime, String endTime, int duration, int courseCount, Integer couponDetailId, Integer payType,
			String weixinAmt, String consumeAmt, Integer productId, String priceTypeCode, String companyAmt,
			String courseAttr, Integer coachId, Integer mealCount, Integer mealCouponCount, Integer dataDictId) throws Exception {
    	logger.info("========================createPayOrderRestructure createOrder start =========================================");
    	ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>();
    	Map<Object, Object> mapParma = new HashMap<>();
    	logger.info("=====userId=" + userInfo.getId() + ">>>>userName=" + userInfo.getNickName() + ">>>>>>.createPayOrder start request parameter ==========");
        logger.info("=payAmount=" + payAmount + ">>>>orderType=" + orderType + ">>>>>>>serviceId=" + serviceId + ">>>>>>personCount=" + personCount);
        logger.info("=weixinAmt=" + weixinAmt + " >>>>consumeAmt=" + consumeAmt +" >>>>>>>>>companyAmt="+companyAmt+"productId="+productId);
        logger.info("=courseAttr=" + courseAttr + " >>>>coachId=" + coachId);
        // 1 基础参数校验
        if (null == userInfo) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("用户信息不存在！");
            return apiResultModel;
        }
        String openid = userInfo.getOpenid();
        if (StringUtil.isEmpty(openid)) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("用户信息openid不存在!");
            return apiResultModel;
        }
        if (StringUtil.isEmpty(payAmount)) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("支付金额不能为空!");
            return apiResultModel;
        }
        Double d_pay_amout = Double.parseDouble(payAmount);
        if (d_pay_amout < 0) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("支付金额不能小于0!");
            return apiResultModel;
        }
        if (StringUtil.isEmpty(orderType)) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("订单类型不能为空!");
            return apiResultModel;
        }
        OrderType ot = OrderType.getOrderType(orderType);
        if (null == ot) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("订单类型错误!");
            return apiResultModel;
        }
        if (StringUtil.isEmpty(serviceId) && !OrderContants.OrderType.private_bespeak.getType().equals(orderType)) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("serviceId不能为空!");
            return apiResultModel;
        }
        // 每笔订单只能是一个人
        if (Integer.valueOf(personCount) != 1) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("订单人数不正确！");
            return apiResultModel;
        }
       

        ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(Integer.valueOf(serviceId));
       
        BigDecimal p_pay_amout = new BigDecimal(payAmount);// 实付金额
        BigDecimal p_primePrice = null;// 原价
        BigDecimal p_price = null;// 会员价
        BigDecimal p_sum_amout = null;
        Long companyStaffId = null;
        CourseInfo courseInfo = null;
        
        // 优惠券判断是否存在和有效
        apiResultModel = checkCouponExist(couponDetailId);
        CouponApiResultModel couponApiResultModel = null;
        if(apiResultModel.getRet() == apiResultModel.RET_ERROR){
        	return apiResultModel;
        }else{
        	couponApiResultModel = (CouponApiResultModel) apiResultModel.getData();
        }
        // 课程类型进行校验 订单类型的校验start 
        //团课
        if(OrderContants.OrderType.team_course.getType().equals(orderType.trim())){
        	
			// 1课程校验是否通过
			apiResultModel = teamCourseOrderRestructure(userInfo, servicePrice, personCount);
			// 2校验课程不通过
			if (apiResultModel.getRet() == apiResultModel.RET_ERROR) {
				return apiResultModel;
			}
			// 校验是否拥有年卡
			
		}
        // 私教
        else if(OrderContants.OrderType.pt.getType().equals(orderType.trim())){
        	//私教购买次数限制课程校验
            if (userInfo != null && userInfo.getId() != null && servicePrice !=null) {
                int boughtOne = orderInfoMapper.queryOrderLimitByCourseIdAndUserId(servicePrice.getCourseId(), userInfo.getId());
                if (boughtOne == 1) {
                    apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg("亲爱的用户，该课程只能购买1次，您已购买过1次，请勿重复购买!");
                    return apiResultModel;
                }
                 courseInfo =    courseInfoMapper.queryCourseByServiceId(Integer.valueOf(serviceId.trim()));
                //如果私教课程与系统配置课程不一致

                if(courseCount < courseInfo.getPeriods().intValue()){
                    apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg("亲爱的用户，您购买的课程不能小于规定课程数量");
                    return  apiResultModel;
                }
                if(courseInfo!=null){
                    if(courseInfo.getMealCount()!=0 && courseInfo.getMealCount() > mealCouponCount){
                        apiResultModel.setRet(ApiResultModel.RET_ERROR);
                        apiResultModel.setMsg("亲爱的用户，你的餐券数量输入的不正确！");
                        return apiResultModel;
                    }
                }else{
                    apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg("亲爱的用户，您预订的课程不存在！");
                    return apiResultModel;
                }
                
               

            }
		}
        else if(OrderContants.OrderType.fun_camp.getType().equals(orderType.trim())){
        	
        	Integer hasCourseOrder = orderInfoMapper.checkUserIsHasThisCourseOrderByCourseIdAndUserIdAndOrderType(servicePrice.getCourseId(), userInfo.getId(), Integer.valueOf(orderType));
        	if(hasCourseOrder > 0) {
        		apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.CANNOT_REPEAT_PURCHASE_COURSE_ORDER.getCode());
                apiResultModel.setMsg(ErrorCodeConstants.Code.CANNOT_REPEAT_PURCHASE_COURSE_ORDER.getMessage());
                logger.info("=================teamCourseOrderRestructure:user Has been purchased error_code:"+ErrorCodeConstants.Code.CANNOT_REPEAT_PURCHASE_COURSE_ORDER.getMessage());
                return apiResultModel;
        	}
		}
        // 自助健身
		else if(OrderContants.OrderType.selffit.getType().equals(orderType.trim())){
			apiResultModel = selfOrderRestructure(userInfo, servicePrice, personCount, startTime, endTime, duration, storeId,orderType,payAmount);
			if(apiResultModel.getRet() == apiResultModel.RET_ERROR){
				return apiResultModel;
			}
			
		}
		/*else if(OrderContants.OrderType.vip_order.getType().equals(orderType.trim())){
			// 不做判断
			
		}else if(OrderContants.OrderType.user_account.getType().equals(orderType.trim())){
			// 不做判断
		}*/
        // 包月卡的校验
		else if(OrderContants.OrderType.monthly_card.getType().equals(orderType.trim()) && productId > 1){
			ProductService ps = productServiceMapper.selectById(productId);
			ProductServiceDetail psd = productServiceDetailMapper.selectById(serviceId);
			if(ps != null && psd != null && psd.getPdStatus() == UserProductServiceConstants.ISVALID){
				UserProductService userProductService = userProductServiceMapper.queryUserProductServiceByUserIdAndType(userInfo.getId(),ps.getPServiceType());
				// 该包月卡已存在但是未到开通时间
				if(userProductService != null 
							&& userProductService.getIsvalid() == UserProductServiceConstants.ISNOTVALID
							&& userProductService.getBeginDate().compareTo(new Date()) > 0){
					apiResultModel.setErrorCode(ErrorCodeConstants.Code.MONTHLY_CARD_NOT_OPEN.getCode());
					apiResultModel.setMsg(ErrorCodeConstants.Code.MONTHLY_CARD_NOT_OPEN.getMessage());
					apiResultModel.setRet(apiResultModel.RET_ERROR);
					logger.info("==========================createPayOrderRestructure error: monthly card not open========================");
					return apiResultModel;
				}
			}else{
				apiResultModel.setErrorCode(ErrorCodeConstants.Code.MONTHLY_CARD_IS_NOT_FOUND.getCode());
				apiResultModel.setMsg(ErrorCodeConstants.Code.MONTHLY_CARD_IS_NOT_FOUND.getMessage());
				apiResultModel.setRet(apiResultModel.RET_ERROR);
				logger.info("==========================createPayOrderRestructure error: monthly card is not found========================");
				return apiResultModel;
			}
			
		}else if(OrderContants.OrderType.private_bespeak.getType().equals(orderType)){
			apiResultModel = checkPrivateBespeak(coachId, userInfo.getId(), apiResultModel, dataDictId, storeId);
			if(apiResultModel.getRet() == apiResultModel.RET_ERROR){
				return apiResultModel;
			}
			Map<String,Object> dataMap = (Map<String, Object>) apiResultModel.getData();
			startTime = (String) dataMap.get("startTime");
			endTime = (String) dataMap.get("endTime");
			
		}/*else if(OrderContants.OrderType.physical_examination.getType().equals(orderType) 
				|| OrderContants.OrderType.secret_experience.getType().equals(orderType)) {
			
			
			
		}*/
       
        // 判断支付方式
        switch (Integer.valueOf(payType)) {
        // 微信在线支付方式
		case OrderContants.PAY_TYPE_WECHAT:
			logger.info("====================pay_type is wechat start =======================================");
			// 如果是微信支付 个人储值卡不能有金额
			if(Integer.valueOf(consumeAmt) > 0.000001){
				apiResultModel.setErrorCode(ErrorCodeConstants.Code.ORDER_PAY_AMOUT_WRONG.getCode());
				apiResultModel.setMsg(ErrorCodeConstants.Code.ORDER_PAY_AMOUT_WRONG.getMessage());
				apiResultModel.setRet(apiResultModel.RET_ERROR);
				logger.info("==========================createPayOrderRestructure error: wechat is pay consumeAmt not greater than 0========================");
				return apiResultModel;
			}
			// 微信支付的时候 微信金额不与实付金额相等 
			if(p_pay_amout.compareTo(new BigDecimal(weixinAmt)) != 0){
				apiResultModel.setErrorCode(ErrorCodeConstants.Code.ORDER_PAY_AMOUT_WRONG.getCode());
				apiResultModel.setMsg(ErrorCodeConstants.Code.ORDER_PAY_AMOUT_WRONG.getMessage());
				apiResultModel.setRet(apiResultModel.RET_ERROR);
				logger.info("==========================createPayOrderRestructure error: wechat is pay weixin not equal to payAmount========================");
				return apiResultModel;
			}
			logger.info("====================pay_type is wechat end =======================================");
			break;
		// 个人储值卡支付方式	
		case OrderContants.PAY_TYPE_PERSON_ACCOUNT:
			logger.info("====================pay_type is person_account start =======================================");
			// 1 判断个人储值卡金额是否足够
			if(userInfo.getAccountAmt().compareTo(p_pay_amout) < 0){
				apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
				apiResultModel.setRet(apiResultModel.RET_ERROR);
				apiResultModel.setLogined(isLogined());
				apiResultModel.setMsg("账户余额不足!");
				logger.info("=========== createPayOrderRestructure error:pay_type person_account 账户余额不足! ==========================");
				return apiResultModel;
			}
			// 2 校验个人储值卡是否与实付金额相等
			if(p_pay_amout.compareTo(new BigDecimal(consumeAmt)) != 0){
				apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
				apiResultModel.setRet(apiResultModel.RET_ERROR);
				apiResultModel.setLogined(isLogined());
				apiResultModel.setMsg("非法操作!");
				logger.info("=========== createPayOrderRestructure error:pay_type consumeAmt not equal payAmout 实付金额不等于个人储值卡金额! ==========================");
				return apiResultModel;
			}
			// 3 校验微信金额是否大于0
			if((new BigDecimal(weixinAmt)).compareTo(BigDecimal.ZERO) != 0){
				apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
				apiResultModel.setRet(apiResultModel.RET_ERROR);
				apiResultModel.setLogined(isLogined());
				apiResultModel.setMsg("非法操作!");
				logger.info("=========== createPayOrderRestructure error:pay_type weixinAmt not equal to 0 个人储值卡支付微信金额不为 0 ! ==========================");
				return apiResultModel;
			}
			// 身份校验 因为都是个人储值卡支付所以就放在这里校验
			apiResultModel = checkUserIsHasYearCardService(userInfo.getId(), courseInfo, Integer.valueOf(orderType));
			if(apiResultModel.getRet() == ApiResultModel.RET_ERROR) {
				return  apiResultModel;
			}
			logger.info("====================pay_type is person_account end =======================================");
			break;
		// 企业支付方式	
		case OrderContants.PAY_TYPE_COMPANY_ACCOUNT:
			apiResultModel = checkPayTypeCompanyWechatAccount(userInfo, payAmount, orderType);
			if(apiResultModel.getRet() == apiResultModel.RET_ERROR){
				return apiResultModel;
			}
			// 判断两边的金额不等
			if(new BigDecimal(payAmount).compareTo(new BigDecimal(companyAmt)) != 0) {
				apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
				apiResultModel.setRet(apiResultModel.RET_ERROR);
				apiResultModel.setLogined(isLogined());
				apiResultModel.setMsg("非法操作!");
				logger.info("=========== createPayOrderRestructure error: 企业实付金额不等于支付金额  ==========================");
				return apiResultModel;
			}
			companyStaffId = (Long) apiResultModel.getData();
			break;
		// 微信+个人 混合支付方式	
		case OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT:
			logger.info("====================pay_type is company_weixin_account start =======================================");
			// 这里其实第一步和第二步是一样的但是为了提示信息更加完善而已
			// 1先是判断个人储值卡金额是否足够
        	if(userInfo.getAccountAmt().compareTo(new BigDecimal(consumeAmt)) < 0){
        		apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg("储值卡金额不足!");
                logger.info("==========createPayOrderRestructure error：user accountAmt Insufficient balance, AccountAmt :"+userInfo.getAccountAmt()+"===consumeAmt:"+consumeAmt);
                return apiResultModel;
        	}
        	// 2先是判断个人储值卡金额是否相等
        	if(userInfo.getAccountAmt().compareTo(new BigDecimal(consumeAmt)) != 0){
        		apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg("储值卡金额不正确!");
                logger.info("==========createPayOrderRestructure error：user AccountAmt :"+userInfo.getAccountAmt()+"===consumeAmt:"+consumeAmt);
                return apiResultModel;
        	}
        	// 3 判断微信支付金额是否相等
        	BigDecimal p_weixinAmt = new BigDecimal(weixinAmt);
        	BigDecimal p_consumeAmt = new BigDecimal(consumeAmt);
        	BigDecimal bd_pay_amout = new BigDecimal(payAmount);
        	if(bd_pay_amout.compareTo(p_weixinAmt.add(p_consumeAmt)) != 0){
        		apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg("微信金额不正确!");
                logger.info("==========createPayOrderRestructure error：payAmount :"+bd_pay_amout+"===consumeAmt:"+consumeAmt+"===weixinAmt"+p_weixinAmt);
                return apiResultModel;
        	}
			logger.info("====================pay_type is company_weixin_account end =======================================");
			break;	
		// 微信支付+企业储值卡支付
		case OrderContants.PAY_TYPE_COMPANY_WECHAT_ACCOUNT:
			apiResultModel = checkPayTypeCompanyWechatAccount(userInfo, companyAmt, orderType);
			if(apiResultModel.getRet() == apiResultModel.RET_ERROR){
				return apiResultModel;
			}
			// 判断两边的金额不等
			if(new BigDecimal(payAmount).compareTo(new BigDecimal(companyAmt).add(new BigDecimal(weixinAmt))) != 0) {
				apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
				apiResultModel.setRet(apiResultModel.RET_ERROR);
				apiResultModel.setLogined(isLogined());
				apiResultModel.setMsg("非法操作!");
				logger.info("=========== createPayOrderRestructure error: 微信金额+企业支付金额 不等于 实付金额  ==========================");
				return apiResultModel;
			}
			companyStaffId = (Long) apiResultModel.getData();
			break;
		// 第6种支付方式
		default:
			break;
		}
        // 统一进行金额校验
		p_sum_amout = this.checkOrderAmount(orderType, serviceId, personCount, userInfo, String.valueOf(duration), couponApiResultModel, courseCount, payType, payAmount, startTime,productId,courseInfo,mealCouponCount,storeId);
		logger.info("=========== createPayOrderRestructure : p_sum_amout: "+p_sum_amout+" ==  p_pay_amout:"+p_pay_amout+"==========================");
		// 校验后台计算的金额和前端传入的金额是否正确
		if(p_sum_amout.compareTo(p_pay_amout) != 0){
			apiResultModel.setErrorCode(ErrorCodeConstants.Code.ORDER_PAY_AMOUT_WRONG.getCode());
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setLogined(isLogined());
			apiResultModel.setMsg(ErrorCodeConstants.Code.ORDER_PAY_AMOUT_WRONG.getMessage());
			logger.info("=========== createPayOrderRestructure : pay_amout is wrong ==========================");
			return apiResultModel;
		}
		// 4创建订单
		Map<Object, Object> map = new HashMap<>();
        String tradeNo = OrderUtil.getOrderNumber(OrderContants.ORDER_SOURCE_WECHAT + "");// 创建订单流水
        String tradeId = this.getTradeId();// 创建交易编号
        String userPwd = this.getUserPwd(storeId);// 创建进店密码
        Integer pwdStuatus = 1;// 设置订单状态为未付款状态
        Date date = new Date();
        Integer version = 0;
        String orderTypeNew = orderType;
        // 因为这里没有 会员身份的概念了 
        if(orderType.equals(OrderContants.OrderType.monthly_card.getType())){
        	ProductServiceDetail productServiceDetail = productServiceDetailMapper.selectById(serviceId);
			ProductService productService = productServiceMapper.selectById(productServiceDetail.getPdProductServiceId());
			// 会员包月卡
			if(UserProductServiceConstants.VIPSERVICE.equals(productService.getPServiceType())) {
				orderTypeNew = "5";
			}else {
				orderTypeNew = orderType;
			}
        	
        }else{
        	orderTypeNew = orderType;
        }
        //创建订单信息
		OrderInfo orderInfo = createOrderInfo(orderTypeNew, tradeNo, date, userInfo.getId(), serviceId, p_pay_amout,
				tradeId, userPwd, pwdStuatus, p_sum_amout, d_pay_amout, Double.valueOf(1), storeId,
				couponApiResultModel, payType, companyStaffId, weixinAmt, consumeAmt, priceTypeCode, companyAmt);
        // 创建进店密码
//        int pwd_bool = createStorePwdByOrderId(orderInfo.getId(), storeId, orderTypeNew, startTime, duration, userPwd, serviceId);
        //创建订单明细信息
        createOrderDetail(orderInfo, courseCount, duration, personCount, startTime, storeId, version, courseAttr, coachId, mealCount, mealCouponCount, null, endTime,null);
        logger.info("=========createOrderDetail is OK ===============================");
        Map<Object, Object> params = new HashMap<>();
        params.clear();
        
		// 5调用微信创建订单接口
        if ((d_pay_amout > 0 && payType.intValue() == OrderContants.PAY_TYPE_WECHAT)){
        	logger.info("go pay wechat");
	        logger.info("request ip is :" + apbillCreateIp + ",tradeNo:" + tradeNo + ",payAmount:" + payAmount + ",openid:" + openid +"weixinAmt:"+weixinAmt);
	        String p_payAmount = (payType.intValue() == OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT ? weixinAmt : payAmount); 
	        map.put("signUrl", TenWeChatGenerator.genPayOrder(OrderContants.OrderType.getOrderType(orderType).getTitle(), tradeNo, p_payAmount, openid, apbillCreateIp)); 
        
        }else if(payType.intValue() == OrderContants.PAY_TYPE_PERSON_ACCOUNT){
        	logger.info("====================use userAccount pay order  =========================================");
            BigDecimal userAccount = userInfo.getAccountAmt().subtract(new BigDecimal(payAmount));
            userInfo.setAccountAmt(userAccount);
            int bool = userService.updateUserInfo(userInfo);
            updatePayOrder(orderInfo.getOrderNumber(), tradeNo);
            // 储值卡消费记录
            insertUserAccountConsume(userInfo, orderInfo.getOrderNumber()); 
            
        }else if(payType.intValue() == OrderContants.PAY_TYPE_COMPANY_ACCOUNT){
        	logger.info("====================use userAccount pay order  =========================================");
            logger.info("======企业储值卡支付订单==use companyAccount pay order  =========================================");
            //更新企业储值账户余额
            boolean result = updatePayOrder(orderInfo.getOrderNumber(), tradeNo);
            logger.info("======企业储值卡支付订单==use companyAccount pay order  ===更新订单状态 -> " + result + "==========");
            //插入企业员工消费表
            orderInfo = orderInfoMapper.queryOrderInfoById(orderInfo.getId());
            insertCompanyStaffConsume(orderInfo.getId(),orderInfo.getPayTime(),orderInfo.getOrderStatus(), payAmount, userInfo, companyStaffId);
            
        }else if(payType.intValue() == OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT){
        	// 先是发起微信支付
			logger.info("go pay wechat");
	        logger.info("request ip is :" + apbillCreateIp + ",tradeNo:" + tradeNo + ",payAmount:" + payAmount + ",openid:" + openid +"weixinAmt:"+weixinAmt);
	        String p_payAmount_t = (payType.intValue() == OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT ? weixinAmt : payAmount); 
	        map.put("signUrl", TenWeChatGenerator.genPayOrder(OrderContants.OrderType.getOrderType(orderType).getTitle(), tradeNo, weixinAmt, openid, apbillCreateIp));
	        // 扣除储值卡金额
            // 储值卡消费记录
            insertUserAccountConsume(userInfo, orderInfo.getOrderNumber());
            
        }else if(payType.intValue() == OrderContants.PAY_TYPE_COMPANY_WECHAT_ACCOUNT){
        	// 1发起微信支付
        	logger.info("go pay wechat");
            logger.info("request ip is :" + apbillCreateIp + ",tradeNo:" + tradeNo + ",payAmount:" + payAmount + ",openid:" + openid +"weixinAmt:"+weixinAmt);
            map.put("signUrl", TenWeChatGenerator.genPayOrder(OrderContants.OrderType.getOrderType(orderType).getTitle(), tradeNo, weixinAmt, openid, apbillCreateIp));  //gymtofun
            
        }else{
        	// 0 元体验课和自助健身 
        	updatePayOrder(orderInfo.getOrderNumber(), tradeNo);
        }
        
        logger.info("====================createPayOrderRestructure createOrder create order is OK=========================================");
        map.put("tradeNo", tradeNo);
        map.put("order", orderInfo);
        apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
        apiResultModel.setData(map);
        logger.info("================================createPayOrderRestructure order create end ====>>>>" + map);
    	return apiResultModel;
    }
    
    /**
     * 团课订单类型的校验
     * @return
     */
    public ApiResultModel teamCourseOrderRestructure(UserInfo userInfo,ServicePrice servicePrice,String personCount){
    	logger.info("=================teamCourseOrderRestructure: buy teamCourse start =======================");
    	ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>();
    	apiResultModel.setRet(apiResultModel.RET_SUCCESS);
    	Map<Object, Object> map = new HashMap<>();
    	// 查询课程属性
    	CourseInfo courseInfo = courseInfoMapper.selectById(servicePrice.getCourseId());
    	if(courseInfo == null){
    		apiResultModel.setErrorCode(ErrorCodeConstants.Code.COURSE_NOT_FOUND.getCode());
    		apiResultModel.setLogined(isLogined());
    		apiResultModel.setRet(apiResultModel.RET_ERROR);
    		apiResultModel.setMsg("您预订的课程不存在!");
    		logger.info("=================teamCourseOrderRestructure》》The course is not find error_msg:"+ErrorCodeConstants.Code.COURSE_NOT_FOUND.getMessage());
    		return apiResultModel;
    	}
    	// 如果是会员独享课程
    	if(courseInfo.getIsVipUsed().intValue() == CourseConstants.IS_VIP_USED){
    		 // 判断订单人数和订单数量
            if (Integer.parseInt(personCount) > 1) {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.COURSE_LIMIT_BUG_ONE.getCode());
                apiResultModel.setMsg("为保障所有檬会员的权益，会员独享类课程每会员限订1笔哦~");
                logger.info("=================teamCourseOrderRestructure:The course is limited to a purchase error_code:"+ErrorCodeConstants.Code.COURSE_LIMIT_BUG_ONE.getCode()+" personCount:"+personCount);
                return apiResultModel;
            }
            // 不是已取消的订单，并且是已付款的订单才计算订单数量
            int orderCount = orderInfoMapper.queryUserNonCancellationOfOrderByServiceId(userInfo.getId(), servicePrice.getId());
            // 判断是否提交过订单，如果订单数量大于0，则表示该用户已预订过该课程。会员独享课每个会员只能有一个订单
            if (orderCount > 0) {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.COURSE_LIMIT_BUG_ONE.getCode());
                apiResultModel.setMsg("亲爱的檬会员，您已购买过该课程。\n为保障所有檬会员的权益，会员独享类课程每会员限订1笔哦~");
                logger.info("=================teamCourseOrderRestructure:user Has been purchased error_code:"+ErrorCodeConstants.Code.COURSE_LIMIT_BUG_ONE.getCode()+" personCount:"+personCount);
                return apiResultModel;
            }
    	}
    	
    	Integer hasCourseOrder = orderInfoMapper.checkUserIsHasThisCourseOrderByCourseIdAndUserIdAndOrderType(courseInfo.getId(), userInfo.getId(), Integer.valueOf(courseInfo.getCourseType()));
    	if(hasCourseOrder > 0) {
    		apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.CANNOT_REPEAT_PURCHASE_COURSE_ORDER.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.CANNOT_REPEAT_PURCHASE_COURSE_ORDER.getMessage());
            logger.info("=================teamCourseOrderRestructure:user Has been purchased error_code:"+ErrorCodeConstants.Code.CANNOT_REPEAT_PURCHASE_COURSE_ORDER.getMessage());
            return apiResultModel;
    	}
    	return apiResultModel;
    }
    
    /**
     * 判断优惠券是否存在
     * @param couponDetailId
     * @return
     * @throws ParseException 
     */
    public ApiResultModel checkCouponExist(Integer couponDetailId){
    	CouponApiResultModel couponApiResultModel= null;
    	ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>();
    	apiResultModel.setRet(apiResultModel.RET_SUCCESS);
    	Map<String, Object> paramsMap = new HashMap<String, Object>();
    	if(couponDetailId > 0){
            paramsMap.put("coupon_detail_id", couponDetailId);
            List<CouponApiResultModel> couponList = couponApiResultMapper.queryUserCouponListBy(paramsMap);
            if (couponList != null && couponList.size() > 0) {
                couponApiResultModel = couponList.get(0);
                // 如果优惠券已使用或者优惠券无效，提示
                if (1 == couponApiResultModel.getIs_used().intValue() || 0 == couponApiResultModel.getIs_valid().intValue()) {
                    apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg("请检查优惠券是否有效!");
                    return apiResultModel;
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date end_use_date = null;
                Date begin_use_date = null;
                Date curDate = null ;
				try {
					end_use_date = sdf.parse(couponApiResultModel.getUse_end_date());
					begin_use_date = sdf.parse(couponApiResultModel.getUse_begin_date());
					curDate = DateUtils.getDateShort(new Date());
				} catch (ParseException e) {
					e.printStackTrace();
				}
                //判断优惠券有效期
                if (end_use_date.before(curDate) || begin_use_date.after(curDate)) {
                    apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg("请检查优惠券是否在有效期内!");
                    return apiResultModel;
                }

            } else {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg("优惠券不存在!");
                return apiResultModel;
            }
    	}
    	apiResultModel.setData(couponApiResultModel);
    	return apiResultModel;
    }
    
    /**
     * 自助健身订单校验
     * @param userInfo
     * @param servicePrice
     * @param personCount
     * @param startTime
     * @param endTime
     * @param duration
     * @return
     */
    public ApiResultModel selfOrderRestructure(UserInfo userInfo,ServicePrice servicePrice,String personCount,String startTime,String endTime,int duration,int storeId,String orderType,String payAmount){
    	ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>();
    	apiResultModel.setRet(apiResultModel.RET_SUCCESS);
    	Map<Object, Object> map = new HashMap<>();
    	//自助健身会员订单校验
    	if (Integer.valueOf(orderType) == 4) {
            //查找用户是否有60分钟内自助健身订单
            Date startTimeTemp = DateUtil.parseUtilDate(startTime, DateUtil.FMT_DATE_YYYYMMDD_HHMMSS);
            List<OrderInfo> orderInfoSelfTemp = orderInfoMapper.queryOrderInfoByStartTime(startTimeTemp, storeId, userInfo.getId());
            if (orderInfoSelfTemp.size() >0) {
                if (payAmount.equals("0")) {
                    //再次下冲突时间内的会员价时提示
                    apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg(ErrorCodeConstants.Code.CANNOT_REPEAT_PURCHASE_SELF_ORDER.getMessage());
                    apiResultModel.setErrorCode(ErrorCodeConstants.Code.CANNOT_REPEAT_PURCHASE_SELF_ORDER.getCode());
                    return apiResultModel;
                }
            }
        }
    	
        Date start_time = null;
        try {
			start_time = DateUtils.toDate(startTime);
		} catch (ParseException e) {
			e.printStackTrace();
			logger.info("=============selfOrderRestructure:"+e.getMessage());
		}
        Long nums = DateUtils.betweenDays(start_time);
        int num = nums.intValue();
        List<DataDict> dataList= dataDictMapper.queryDataDictByDictTypeAndStatus("SELF_FITNESS_TIME","1");
        int durationBool = 0 ;
        for(DataDict d: dataList){
        	if(Integer.valueOf(d.getDictName()) == duration){
        		durationBool = 1 ;
        	}
        }
        logger.info("=============>startTime:" + startTime + "=============>>>>start_time:" + start_time + ">>>>>>>>>>>>>>>>>>>num:" + num);
        if (Math.abs(num) > 40) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("自助健身购买时间不能大于40天！");
            logger.info("=============selfOrderRestructure： 自助健身的时间不能大于40天");
            return apiResultModel;
        }
        if (durationBool == 0) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("自助健身购买时间的时长只能是:\n60,90,120");
            logger.info("=============selfOrderRestructure：自助健身购买时间的时长只能是:60,90,120");
            return apiResultModel;
        }
        
        
    	return apiResultModel;
    }
    
    /**
     * 支付方式金额校验方法二
     * @param userInfo 用户
     * @param orderType 订单类型
     * @param personCount 人数
     * @param payAmount 实付金额
     * @param couponApiResultModel 优惠券
     * @param payType  支付类型 
     * @param productId 产品服务id
     * @return
     * @throws ParseException 
     */
	public BigDecimal checkOrderAmount(String orderType, String serviceId, String personCount, UserInfo userInfo,
			String duration, CouponApiResultModel couponApiResultModel, int courseCount, Integer payType,
			String payAmount, String startTime, Integer productId, CourseInfo courseInfo, Integer mealCouponCout,Integer storeId)
			throws ParseException {
    	ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(Integer.valueOf(serviceId));
    	if(OrderContants.OrderType.monthly_card.getType().equals(orderType) && productId == 1){
    		orderType = "5";
    	}
    	if(OrderContants.OrderType.private_bespeak.getType().equals(orderType)){
    		return BigDecimal.valueOf(0);
    	}
    	BigDecimal all_amt = new BigDecimal(1);
    	Map<String,Object> mapBack = new HashMap<String,Object>();
    	if(Integer.valueOf(orderType) != OrderContants.OrderType.vip_order.getIndex() && 
    			Integer.valueOf(orderType) != OrderContants.OrderType.user_account.getIndex() &&
    			Integer.valueOf(orderType) != OrderContants.OrderType.monthly_card.getIndex()){
    		Date startDate = StringUtil.isEmpty(startTime)?null:new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime);
        	Map<String,Object> mapParam = orderService.checkPayOrderType(userInfo, StringUtil.isEmpty(servicePrice.getCourseId())?0:servicePrice.getCourseId(), servicePrice.getServiceType(),servicePrice.getStoreId(),startDate);//new HashMap<>();
        	BigDecimal p_couponAmount = new BigDecimal(0);
        	int isVip  = 0;
        	List<OrderBookTypeModel> orderBookList = null;
        	if(mapParam != null){
        		
        		// 已经购买过该课程了不能在继续购买了
        		boolean hasCourseOrder = (boolean) mapParam.get("hasCourseOrder");
        		if(hasCourseOrder) {
        			return new BigDecimal("-1");
        		}
        		orderBookList = (List<OrderBookTypeModel>) mapParam.get("payTypeList");
        		if(orderBookList != null){
        			if(OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT == payType.intValue() || payType.intValue() == OrderContants.PAY_TYPE_COMPANY_WECHAT_ACCOUNT){
        				for(OrderBookTypeModel book : orderBookList){
        					//取payType==1的实际单价
        					if(book.getPayType() == 1 && OrderContants.PAY_TYPE_PERSONAL_WECHAT_ACCOUNT == payType.intValue()){
        						all_amt = book.getFinalPrice();
        						all_amt = all_amt.multiply(new BigDecimal(personCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
        						if(!book.isMore() && Integer.valueOf(personCount) > 1){
        							all_amt = BigDecimal.valueOf(-1);
        							logger.info("================= checkOrderAmount error:Do not support many people is pay ========================= payType："+payType);
        							return all_amt;
        						}
        						break;
        					}
        					if(book.getPayType() == 3 && payType.intValue() == OrderContants.PAY_TYPE_COMPANY_WECHAT_ACCOUNT){
        						all_amt = book.getFinalPrice();
        						all_amt = all_amt.multiply(new BigDecimal(personCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
        						if(!book.isMore() && Integer.valueOf(personCount) > 1){
        							all_amt = BigDecimal.valueOf(-1);
        							logger.info("================= checkOrderAmount error:Do not support many people is pay ========================= payType："+payType);
        							return all_amt;
        						}
        						break;
        					}
        				}
        			}else{
        				//取对应支付方式的结果
        				for(OrderBookTypeModel book : orderBookList){
        					// 非混合支付方式
        					if(payType == book.getPayType()){
        						all_amt = book.getFinalPrice();
        						all_amt = all_amt.multiply(new BigDecimal(personCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
        						if(!book.isMore() && Integer.valueOf(personCount) > 1){
        							all_amt = BigDecimal.valueOf(-1);
        							logger.info("================= checkOrderAmount error:Do not support many people is pay ========================= payType："+payType);
        							return all_amt;
        						}
        						break;
        					}
        				}
        			}
        			
        		}
        		// 私教这里做特殊的处理
        		if(OrderContants.OrderType.pt.getType().equals(orderType.trim())){
                    //去餐券价格
                    Map<String,Object> paramMap = new HashMap<>();
                    paramMap.put("serviceType", ServiceConstans.ServiceType.mealCouponService.getType());
                    if(storeId>0){
                        paramMap.put("storeId",storeId);
                    }
                    List<ServicePrice> mealCouponServicePriceList = servicePriceMapper.selectServicePriceBy(paramMap);
                    BigDecimal mealCouponPrice = ServiceConstans.defaultMealCouponPrice;
                    if(mealCouponServicePriceList!=null && mealCouponServicePriceList.size()>0){
                        mealCouponPrice= mealCouponServicePriceList.get(0).getPrice();
                    }
        		    BigDecimal mealPrice = new BigDecimal(mealCouponCout-courseInfo.getMealCount()).multiply(mealCouponPrice);
        		    // 获取到售价  之后  利用 （ 自定义课时数 - 总课时数 ） x 单价
        		    all_amt = all_amt.add(new BigDecimal(courseCount - courseInfo.getPeriods()).multiply(ServiceConstans.defaultPtCoursePrice));
                    all_amt = all_amt.add(mealPrice);
        		}
        	}
        	if(couponApiResultModel != null){
        		// 现金券
        		if(couponApiResultModel.getCoupon_type().intValue() == CouponConstants.CouponType_Money.intValue()){
        			p_couponAmount = p_couponAmount.add(couponApiResultModel.getCash_money());
        			if(p_couponAmount.compareTo(all_amt) > 0){
        				all_amt = BigDecimal.valueOf(0);
        			}else{
        				all_amt = all_amt.subtract(p_couponAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
        			}
        			
        		}else if(couponApiResultModel.getCoupon_type().intValue() == CouponConstants.CouponType_Course.intValue()){
        		// 课程体验券
        			all_amt = all_amt.multiply(BigDecimal.valueOf(0));
        		}else if(couponApiResultModel.getCoupon_type().intValue() == CouponConstants.CouponType_Discount.intValue()){
        		//折扣券	
        			all_amt = all_amt.multiply(couponApiResultModel.getDiscount()).setScale(2, BigDecimal.ROUND_HALF_UP);
        		}else{
        			all_amt = all_amt.multiply(BigDecimal.valueOf(-1));
        		}
            }
    	}else if(Integer.valueOf(orderType) == OrderContants.OrderType.vip_order.getIndex()){
    		 //购买会员订单
            /*UserDiscount userDiscount = servicePriceMapper.getUserDiscountById(Integer.valueOf(serviceId));
            all_amt = userDiscount.getPrimePrice().multiply(BigDecimal.valueOf(userDiscount.getDiscount()));*/
    		ProductServiceDetail psd = productServiceDetailMapper.selectById(serviceId);
    		all_amt = psd.getPdPrimePrice().multiply(BigDecimal.valueOf(psd.getPdDiscount()));
    	}else if(Integer.valueOf(orderType) == OrderContants.OrderType.user_account.getIndex()){
    		// 1 先根据serviceId查询对应的面额和实到金额
            RechargeDiscount rechargeDiscount = null;
            rechargeDiscount = rechargeDiscountMapper.selectById(Integer.valueOf(serviceId));
            all_amt = rechargeDiscount.getFaceAmt();
    	}else if(Integer.valueOf(orderType) == OrderContants.OrderType.monthly_card.getIndex()){
    		// 包月卡订单
    		ProductServiceDetail psd = productServiceDetailMapper.selectById(serviceId);
    		all_amt = psd.getPdPrimePrice().multiply(BigDecimal.valueOf(psd.getPdDiscount()));
    	}else{
    		all_amt = BigDecimal.valueOf(-1);
    	}
    	return all_amt;
    }

    /**
     * 创建日志记录信息
     */
	@Override
	public void createPayLogs(int userId, String serviceType, String logs) {
		orderInfoMapper.createPayLogs(userId, serviceType, logs);
	}
	
	/**
	 * 创建包月卡日志记录表
	 */
	public void createVipPurchaseLog(String orderNumber,OrderInfoResultModel orderInfoResultModel){
		logger.info("====================================== createVipPurchaseLog start ============================orderNumber:"+orderNumber);
		OrderInfo orderInfo = orderInfoMapper.queryOrderInfoByNumber(orderNumber);
		if (StringUtil.isEquals(orderInfo.getOrderType(), OrderContants.OrderType.vip_order.getType())
				|| StringUtil.isEquals(orderInfo.getOrderType(), OrderContants.OrderType.monthly_card.getType())) {
			// 根据服务id查询产品明细
			ProductServiceDetail productServiceDetail = productServiceDetailMapper.selectById(orderInfo.getServiceId());
			ProductService productService = productServiceMapper.selectById(productServiceDetail.getPdProductServiceId());
			UserProductService userProductService = null;
			int isvalid = 1 ;// 判断该卡是否需要开通
			// 判断是否是 会员 还是包月卡 
			if(productService.getPServiceType().equals(UserProductServiceConstants.productServiceType.vip.getType())){
				userProductService = userProductServiceMapper.queryUserProductServiceToUserLevel(orderInfo.getUserId());
			}else{
				userProductService = userProductServiceMapper.queryUserProductServiceByUserIdAndType(orderInfo.getUserId(),productService.getPServiceType());
			}
			
			if(productServiceDetail != null){
				VipPurchaseLog memberPurchaseLog = new VipPurchaseLog();
	            memberPurchaseLog.setOrderId(orderInfo.getId());
	            memberPurchaseLog.setUserId(orderInfo.getUserId());
	            memberPurchaseLog.setLevel(orderInfoResultModel.getUserInfo().getLevel());
	            memberPurchaseLog.setProductServiceId(productServiceDetail.getPdProductServiceId());
	            memberPurchaseLog.setCreatedBy(orderInfo.getUserId());
	            memberPurchaseLog.setCreatedTime(new Date());
	            
	            // 获取用户的月卡的开始时间
                int vipNum = 0;
                if (!productServiceDetail.getPdDateline().before(DateUtils.getDateShort(new Date()))) {
                    vipNum = vipNum + productServiceDetail.getPdFreeday();
                }
                // 个人储值卡方式充值
                if (orderInfo.getPayType() == OrderContants.PAY_TYPE_PERSON_ACCOUNT) {
                    memberPurchaseLog.setPurchaseType(OrderContants.PAY_TYPE_PERSON_ACCOUNT);
                // 企业储值卡方式充值 blank
                } else if(orderInfo.getPayType() == OrderContants.PAY_TYPE_COMPANY_ACCOUNT) {
                    memberPurchaseLog.setPurchaseType(4);// 这里设置为4 因为 3 是檬会员体验卷
                } else {
                    memberPurchaseLog.setPurchaseType(OrderContants.PAY_TYPE_WECHAT);
                }

                UserInfo userInfo = userInfoMapper.selectById(orderInfo.getUserId());
                Date end_date;
                Date presell_date = null;
                Date beginDate = null;
                try {
                	// 活动日期截止时间
                	presell_date = productServiceDetail.getPdDateline() == null ? new Date():productServiceDetail.getPdDateline();
                } catch (Exception e) {
                    e.printStackTrace();
                }
               
                // 如果没有的话就插入一条信息 是新增的 
                if(userProductService == null){
                	end_date = DateUtils.getDateShort(new Date());
                	beginDate = DateUtils.getDateShort(new Date());
                }else{
                	// 续费
                    //防止空指针异常
                    if(userProductService.getBeginDate() == null){
                        userProductService.setBeginDate(DateUtils.getDateShort(new Date()));
                    }
                    if(userProductService.getEndDate() == null){
                        userProductService.setEndDate(DateUtils.getDateShort(new Date()));
                    }
                    // 如果会员身份是有效的 
                    if(userProductService.getIsvalid() == UserProductServiceConstants.ISVALID
                    		&& UserProductServiceConstants.productServiceType.vip.getType().equals(userProductService.getProductServiceType())){
                        end_date = DateUtils.getDateShort(userProductService.getEndDate() == null ? new Date():userProductService.getEndDate());
                    	beginDate = DateUtils.getDateShort(userProductService.getBeginDate() == null ? new Date() : userProductService.getBeginDate());
                    }else if(Integer.valueOf(userProductService.getProductServiceType()) > UserProductServiceConstants.productServiceType.vip.getIndex()
                    		&& userProductService.getIsvalid() == UserProductServiceConstants.ISVALID) {
                    	// 包月卡 续费
                    	end_date = DateUtils.getDateShort(userProductService.getEndDate() == null ? new Date():userProductService.getEndDate());
                     	beginDate = DateUtils.getDateShort(userProductService.getBeginDate() == null ? new Date() : userProductService.getBeginDate());
                    }else{
                    	// 这里的无效还分为两种  一种是已购买了但是未到开通时间 另一种就是没有该服务 
                    	// 该用户已经有了该包月卡但是未开通
                    	if(userProductService.getBeginDate().compareTo(new Date()) > 0){
                    		end_date = userProductService.getEndDate();
                            userInfo.setVipStartTime(end_date);
                            beginDate = userProductService.getBeginDate();
                            isvalid = 0 ;
                    	}else{
                    		end_date = DateUtils.getDateShort(new Date());
                            userInfo.setVipStartTime(end_date);
                            beginDate = DateUtils.getDateShort(new Date());
                    	}
                    	
                    }
                }
                
                // 第一次购买会员的时候是以当前系统时间作为开始时间的
                if (end_date.compareTo(presell_date) < 0) {
                    end_date = presell_date;
                    beginDate = presell_date;
                    isvalid = 0;
                }
                
                //设置日志会员开始日期
                memberPurchaseLog.setStartTime(end_date);
                
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(end_date);
               
                rightNow.add(Calendar.MONTH, Integer.valueOf(productServiceDetail.getPdType()));// 日期加1个月
                int num = 1;
                if (userProductService != null && userProductService.getEndDate() != null && userProductService.getEndDate().after(new Date())) {
                    //续费会员订单 不多加一天
                    num = 0;
                }

                if (!productServiceDetail.getPdDateline().before(DateUtils.getDateShort(new Date()))) {
                    num = num + productServiceDetail.getPdFreeday();
                }
                rightNow.add(Calendar.DATE, num);
                // 日期加1一天
                end_date = rightNow.getTime();
                if(userProductService != null  
                		&& userProductService.getProductServiceType().equals(UserProductServiceConstants.productServiceType.vip.getType())
                		|| userProductService != null
                		&& userProductService.getProductServiceType().equals(UserProductServiceConstants.productServiceType.user.getType())){
                	userInfo.setVipStartTime(beginDate);
                	userInfo.setLevel(2);
               	 	userInfo.setVipEndTime(end_date);
               	 	int bool = userInfoMapper.updateSelectiveById(userInfo);
	               	if (bool == 1) {
	                    this.setUserInfo(userInfo);
	                }
                }
                memberPurchaseLog.setEndTime(end_date);
                int molCount = vipPurchaseLogMapper.insert(memberPurchaseLog);
                if(userProductService == null){
                	userProductService = new UserProductService();
                }
                // 插入或者更新用户产品服务表
                userProductService.setBeginDate(beginDate);
            	userProductService.setEndDate(memberPurchaseLog.getEndTime());
            	userProductService.setIsvaild(isvalid);
            	userProductService.setProductServiceType(productService.getPServiceType());
            	userProductService.setUserId(orderInfo.getUserId());
                if(userProductService.getId() == null){
                	userProductService.setCreatedBy(orderInfo.getUserId());
                	userProductService.setCreatedTime(new Date());
                	userProductServiceMapper.insert(userProductService);
                }else{
                	userProductService.setUpdatedTime(new Date());
                	userProductService.setUpdatedBy(orderInfo.getUserId());
                	userProductServiceMapper.updateSelectiveById(userProductService);
                }
                logger.info("=====> buy vip  orderInfo end ================" + userInfo);
                /*templateSendService.sendOpenVIPSuccTemplateMsg(orderInfo.getId());*/
                templateSendService.sendOpenVIPSuccTemplateMsgNew(orderInfo.getId(), memberPurchaseLog.getStartTime(), memberPurchaseLog.getEndTime(),num);
			}else{
				logger.info("====================================== createVipPurchaseLog error 查询不到产品明细====================");
			}
		}
		logger.info("====================================== createVipPurchaseLog start ============================orderNumber:"+orderNumber);
	}
	
	/**
	 * 企业支付校验
	 * @param userInfo	用户
	 * @param payAmount	企业消费金额
	 * @param orderType	订单类型
	 * @return
	 */
	public ApiResultModel checkPayTypeCompanyWechatAccount(UserInfo userInfo, String payAmount, String orderType){
		logger.info("====================pay_type is company_account start =======================================");
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		Long companyStaffId = null;
		//企业储值卡账户消费 blank
        CompanyStaff companyStaff = companyStaffMapper.selectCompanyPaymentDetailByUserId(userInfo.getId());
        if (companyStaff != null ) {
            if (companyStaff.getCompanyCurrentLeftAmount().compareTo(new BigDecimal(payAmount)) < 0
                    || companyStaff.getCurrentLeftAmount().compareTo(new BigDecimal(payAmount)) < 0) {
                //企业支付单余额不足
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg("企业账户余额不足或员工当月可用余额不足");
                logger.info("======================createPayOrderRestructure error : compan is Insufficient balance =====================");
                return apiResultModel;
            } else {
                //判断订单类型是否允许使用企业储值账户
                if (companyStaff.getIsBuyTypeLimit().equals(0)) {
                    //课程限制校验
                    if (orderType.equals("1") && companyStaff.getLimitTeamCourse().equals(0)
                            || orderType.equals("2") && companyStaff.getLimitSecretCourse().equals(0)
                            || orderType.equals("3") && companyStaff.getLimitCampCourse().equals(0)
                            || orderType.equals("4") && companyStaff.getLimitSelfCourse().equals(0)
                            || orderType.equals("5") && companyStaff.getLimitVip().equals(0)) {

                        apiResultModel.setRet(ApiResultModel.RET_ERROR);
                        apiResultModel.setMsg("当前订单不支持企业储值支付");
                        logger.info("======================createPayOrderRestructure error :  can not use the compan to pay =====================");
                        return apiResultModel;
                    }
                }
                companyStaffId = companyStaff.getId();
                apiResultModel.setRet(apiResultModel.RET_SUCCESS);
                apiResultModel.setData(companyStaffId);
                logger.info("使用企业支付 并成功获取企业员工ID ---> " + companyStaffId);
            }
            
            // 判断该用户  add timo
            // 上面做了企业余额的判断了 	这里做一下月度限额的校验
            if(companyStaff.getIsMonthlyLimit() != null && companyStaff.getIsMonthlyLimit() == 0){
            	// 校验月度限额是否足够
            	if(companyStaff.getMonthlyLimit().compareTo(new BigDecimal(payAmount))< 0){
            		apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg("员工本月配额不足！");
                    logger.info("======================createPayOrderRestructure error :  The company's balance this month is insufficient  =====================");
                    return apiResultModel;
            	}
            }
            // 这里是做了月度总限额校验   
            if(companyStaff.getCompanyIsMonthlyTotalLimit() != null && companyStaff.getCompanyIsMonthlyTotalLimit().compareTo(BigDecimal.ZERO) == 0){
            	if(companyStaff.getCompanyMonthlyTotalLimit().compareTo(new BigDecimal(payAmount)) < 0){
            		apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg("企业本月全员配额已满！");
                    logger.info("======================createPayOrderRestructure error :  The current monthly balance of the firm is insufficient  =====================");
                    return apiResultModel;
            	}
            }
            
            
        }else{
        	apiResultModel.setRet(apiResultModel.RET_ERROR);
        	apiResultModel.setMsg(ErrorCodeConstants.Code.USER_IS_NOT_COMPANY_EMPLOYEES.getMessage());
        	apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_IS_NOT_COMPANY_EMPLOYEES.getCode());
        }
		logger.info("====================pay_type is company_account end =======================================");
		return apiResultModel;
	}
	
	/**
	 * 插入企业员工用户消费记录表
	 * @param //orderInfo			订单
	 * @param payAmount			企业储值卡实付金额
	 * @param userInfo			用户
	 * @param companyStaffId	企业员工Id
	 */
	public void insertCompanyStaffConsume(Integer orderId,Date payTime,String orderStatus, String payAmount,UserInfo userInfo, Long companyStaffId){
		logger.info("============================== insertCompanyStaffConsume start ==================================");
		CompanyStaffConsume companyStaffConsume = new CompanyStaffConsume();
        companyStaffConsume.setAmount(new BigDecimal(payAmount));
        companyStaffConsume.setPayTime(payTime);
        companyStaffConsume.setOrderId(orderId);
        companyStaffConsume.setOrderStatus(Integer.valueOf(orderStatus));
        companyStaffConsume.setUserId(userInfo.getId());
        companyStaffConsume.setCompanyStaffId(companyStaffId);
        boolean cscr = companyStaffConsumeMapper.insertSelective(companyStaffConsume) >0;
        logger.info("======企业储值卡支付订单==use companyAccount pay order  ===插入企业员工订单表状态 -> " + cscr + "==========");
        logger.info("============================ insertCompanyStaffConsume end ==================================");
	}
	
	/**
	 * 预约私教订单校验
	 * @param coachId
	 * @param apiResultModel
	 * @return
	 */
	public ApiResultModel checkPrivateBespeak(Integer coachId,Integer userId, ApiResultModel apiResultModel, Integer dataDictId, Integer storeId){
		Map<String,Object> resultMap = new HashMap<>();
		// 判断是不是 在同一家门店有未过期的到店体验
		Integer orderCount = orderInfoMapper.queryOrderCountByCoachIdAndUserIdAndOrderTypeAndOrderStatusToDay(userId, coachId, 1, 11, storeId);
		if(orderCount > 0){
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setMsg(ErrorCodeConstants.Code.CANNOT_REPEAT_PURCHASE_PRIVATE_CONSULT.getMessage());
			apiResultModel.setErrorCode(ErrorCodeConstants.Code.CANNOT_REPEAT_PURCHASE_PRIVATE_CONSULT.getCode());
			return apiResultModel;
		}
		DataDict dataDict = dataDictMapper.selectById(dataDictId);
		if(dataDict == null ) {
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setMsg("请选择预约正确时间！");
			return apiResultModel;
		}
		// 
		String[] dataTime = dataDict.getDictCode().split("-");
		Date startDate = DateUtils.AddDays(new Date(), 1);
		String date = DateUtils.toDateString(startDate);
		String startTime = date + " " +dataTime[0] + ":00";
		String endTime = date + " " +dataTime[1] + ":00";
		resultMap.put("startTime", startTime);
		resultMap.put("endTime", endTime);
		apiResultModel.setData(resultMap);
		
		return apiResultModel;
	}
	
	/**
	 * 体测订单和私教预约订单
	 * @param //userId
	 * @param //orderId
	 * @param orderInfoResultModel
	 */
	public void assignTasksToCoach(OrderInfoResultModel orderInfoResultModel){
		Integer coachId = orderInfoResultModel.getOrderDetail().getCoachId();
		logger.info("===================== assignTasksToCoach coachId 1 :"+coachId);
		if(coachId == 0){
			coachId = coachPrivateSortService.checkAndReturnNextCoachId(orderInfoResultModel.getId(), orderInfoResultModel.getUserId());
			logger.info("===================== assignTasksToCoach coachId 2:"+coachId);
		}
    	StoreCoach storeCoach = new StoreCoach();
    	storeCoach.setCoachId(coachId);
    	Integer storeId = storeCoachMapper.queryStoreIdByCoachId(coachId);
    	OrderDetail orderDetail = orderInfoResultModel.getOrderDetail();
    	orderDetail.setCoachId(coachId);
    	if(orderDetail != null && orderDetail.getStoreId() == 0){
    		orderDetail.setStoreId(storeId);
    	}
    	orderDetailMapper.updateSelectiveById(orderDetail);
    	coachPrivateSortService.updateCoachSort(orderInfoResultModel.getId());
    	sendShortMessage(orderInfoResultModel.getUserInfo(), orderInfoResultModel.getOrderType(), orderInfoResultModel.getOrderDetail().getCourseAttr(), coachId);
    	
	}
	
	/**
	 * 发送短信
	 * @param userInfo
	 */
	public void sendShortMessage(UserInfo userInfo,Integer orderType,String courseAttr, Integer coachId){
		CoachInfo coachInfo = coachInfoMapper.selectById(coachId);
		if(!StringUtil.isEmpty(userInfo) && coachInfo != null && !StringUtil.isEmpty(coachInfo.getMobile())){
			if(orderType.intValue() == OrderContants.OrderType.physical_examination.getIndex()){
				SmsUtil.sendCoachPrivateBodyExaminationNotificationSms(userInfo.getNickName(), userInfo.getMobile(),coachInfo.getMobile());
			}else if(orderType.intValue() == OrderContants.OrderType.secret_experience.getIndex()){
				SmsUtil.sendCoachPrivateExperienceNotificationSms(userInfo.getNickName(), userInfo.getMobile(),coachInfo.getMobile());
			}else if(orderType.intValue() == OrderContants.OrderType.private_bespeak.getIndex()){
//				SmsUtil.sendTemplateCoachPrivateCourseNotificationSms(userInfo.getNickName(), userInfo.getMobile(),"",coachInfo.getMobile());
			}
			
		}
	}
	
	/**
	 * 用户线下购餐 
	 */
	@Override
	public ApiResultModel createPayMealOrder(UserInfo adminMealUserInfo, Integer userId, String orderType,
			String payType, BigDecimal payAmount, Integer mealCount, String couponDetailId) throws Exception{
		logger.info("================================== createPayMealOrder start ==========================");
		logger.info("====param>>>userId:"+userId);
		logger.info("====param>>>payAmount:"+payAmount);
		logger.info("====param>>>payType:"+payType);
		logger.info("====param>>>adminMealUserInfo:"+adminMealUserInfo.getId());
		
		
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		Map<String,Object> resultMap = new HashMap<>();
		UserInfo userInfo = userService.selectById(userId);
		Date createDate = new Date(); 
		CouponApiResultModel couponApiResultModel = null; 
		String tradeNo = OrderUtil.getOrderNumber(OrderContants.ORDER_SOURCE_WECHAT + "");
	    String tradeId = this.getTradeId();
	    SysUser sysUser = sysUserMapper.querySysUserByMobile(adminMealUserInfo.getMobile());
	    Integer storeId = 0 ;
	    // 查询价格
	    ServicePrice servicePrice = servicePriceMapper.queryServicePriceByServiceTypeOne(Integer.valueOf(OrderContants.OrderType.meal.getIndex()));
		
	    // step 1	 校验参数以及金额
		checkCreateMealOrder(adminMealUserInfo, userInfo, orderType, payType, payAmount, mealCount, couponDetailId, servicePrice, sysUser);
		storeId = sysUser.getStoreId(); 
		// step 2 	创建订单
		OrderInfo orderInfo = createOrderInfo(orderType, tradeNo, createDate, userId, servicePrice.getId().toString(), payAmount, tradeId, null,
				OrderContants.OrderStatus.NORMAL.getIndex(), payAmount, payAmount.doubleValue(), Double.valueOf(1), storeId, couponApiResultModel, Integer.valueOf(payType),
				null, "0", payAmount.toString(), "1", "0");
		
		// step 3 创建订单明细信息 表示是到店购餐
		createOrderDetail(orderInfo, mealCount, 0, "1", DateUtils.toDateHMS(createDate), storeId, 1, "", null, mealCount, null, 1, DateUtils.toDateHMS(createDate), adminMealUserInfo.getId());
		
		// step 4 	创建个人消费记录 
		insertUserAccountConsume(userInfo, orderInfo.getOrderNumber());
		
		// step 5 修改订单状态
		boolean payStatus = updatePayOrder(orderInfo.getOrderNumber(), orderInfo.getTradeNo());
		
		// step 6 是否成功支付
		// 付款成功之后返回给前端的展示字段
		if(payStatus) {
			resultMap.put("orderId", orderInfo.getId());
			resultMap.put("payAmount", orderInfo.getAmount());
			resultMap.put("userName", userInfo.getNickName());
			resultMap.put("payTime", orderInfo.getCreatedTime()); // 这里没有用patTime 是因为 在修改订单状态里面没有返回  就用了订单创建时间
			resultMap.put("orderNumber", orderInfo.getOrderNumber());
			apiResultModel.setData(resultMap);
			apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
			apiResultModel.setMsg("支付成功！");
		}else {
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setMsg("支付失败！");
		}
		logger.info("================================== createPayMealOrder end ==========================");
		return apiResultModel;
	}
	
	// 校验订单
	public void checkCreateMealOrder(UserInfo adminMealUserInfo, UserInfo userInfo , String orderType,
			String payType, BigDecimal payAmount, Integer mealCount, String couponDetailId , ServicePrice servicePrice, SysUser sysUser) throws Exception {
		BigDecimal minPayAmount = new BigDecimal("10000"); //  设置一个默认的最小金额 防止程序报错
		//  从字典表中 获取餐的最小金额
		List<DataDict> dataDictList = dataDictService.queryDataDicts("MEAL_MIN_AMOUNT");
		if(dataDictList.size() > 0 && dataDictList != null) {
			minPayAmount = new BigDecimal(dataDictList.get(0).getDictCode());
		}
		
		// 支付金额 不能小于规定的最小金额
		if(payAmount.setScale(2, BigDecimal.ROUND_HALF_UP).compareTo(minPayAmount) < 0) {
			throw new Exception("请输入正确的支付金额!");
		}
		
		if(servicePrice == null) {
			throw new Exception("该成品不存在!");
		}
		
		if(userInfo == null) {
			throw new Exception("用户不存在!");
		}
		
		if(mealCount < 1) {
			throw new Exception("餐券数量不能小于1");
		}
		
		if(sysUser == null) {
			throw new Exception("你不是管理员！");
		}
		// 餐支付权限
		DataDict payMealRole = dataDictService.queryDataDictByDictTypeAndDictCode("PAY_MEAL_ROLE",
				sysUser.getRoleId().toString());
		
		// 这里只有餐饮权限的同事才有权限
		// 判断该该角色是否拥有权限  判断其状态是否有效
		if (payMealRole == null || (payMealRole != null && !"1".equals(payMealRole.getStatus()))) {
			throw new Exception("你没有餐饮扫码扣款权限！");
		}
		
		// 是收营员的时候 门店id是不能为空的
		if(sysUser.getStoreId() == null) {
			throw new Exception("没有指定餐饮门店！请联系管理人员添加门店权限");
		}
		
		// 金额校验
		// 校验用户金额
		checkCreateMealUserAccount(userInfo, payAmount);
		
	}
	
	// 校验购买用户的账户金额是否足够支付
	public void checkCreateMealUserAccount(UserInfo userInfo , BigDecimal payAmount) throws Exception {
		if(userInfo.getAccountAmt().compareTo(payAmount) < 0) {
			throw new Exception("余额不足，请充值！");
		}
	}
	
	/**
	 * 创建日志文件方法重构
	 * @param orderNumber
	 * @param orderInfoResultModel
	 */
	public void createVipPurchaseLogRestructure(String orderNumber,OrderInfoResultModel orderInfoResultModel) {
		logger.info("============== createVipPurchaseLogRestructure start =====================");
		OrderInfo orderInfo = orderInfoMapper.queryOrderInfoByNumber(orderNumber);
		// 会员包月卡
		if(OrderContants.OrderType.vip_order.getIndex() == orderInfo.getOrderType().intValue()) {
			createVipPurchaseLog(orderNumber,orderInfoResultModel);
			// 后面重构的时候这个方法在写的吧
//			cteateVipLevelCardPurchaseLog();
		}
		// 包月卡 
		else if(OrderContants.OrderType.monthly_card.getIndex() == orderInfo.getOrderType().intValue()) {
			// 先查询该用户是否拥有改包月卡
			createMonthlyCardPurchaseLog(orderInfo, orderInfoResultModel, true);
		}
		logger.info("============== createVipPurchaseLogRestructure start =====================");
	}
	
	// 这里先预留 到时候有会员卡的时候在重构 
	public void cteateVipLevelCardPurchaseLog(OrderInfo orderInfo,OrderInfoResultModel orderInfoResultModel) {
		// 根据服务id查询产品明细
		ProductServiceDetail productServiceDetail = productServiceDetailMapper.selectById(orderInfo.getServiceId());
		// 获取包月卡产品服务
		ProductService productService = productServiceMapper.selectById(productServiceDetail.getPdProductServiceId());
		// 获取用户产品服务信息
		UserProductService userProductService = userProductServiceMapper.queryUserProductServiceToUserLevel(orderInfo.getUserId());
		UserInfo userInfo = userInfoMapper.selectById(orderInfo.getUserId());
		// 非会员身份
		if(userInfo.getLevel() == UserProductServiceConstants.productServiceType.user.getIndex()) {
			// 非会员身份的用户就是需要升级为会员的
			userInfo.setLevel(UserConstants.UserLevel.vip.getIndex());
		}else {
			// 会员身份 续费
			
		}
		
	}
	
	/**
	 * 创建包月卡日志记录消息
	 * 并且修改了用户可拥有的服务信息 
	 */
	public void createMonthlyCardPurchaseLog(OrderInfo orderInfo, OrderInfoResultModel orderInfoResultModel, boolean sendMsg) {
		// 根据服务id查询产品明细
		ProductServiceDetail productServiceDetail = productServiceDetailMapper.selectById(orderInfo.getServiceId());
		
		// 获取包月卡产品服务
		ProductService productService = productServiceMapper.selectById(productServiceDetail.getPdProductServiceId());
		// 获取用户产品服务信息
		UserProductService userProductService = userProductServiceMapper.queryUserProductServiceByUserIdAndType(orderInfo.getUserId(),
				productService.getPServiceType());
		Date endDate = DateUtils.getDateShort(new Date());	// 结束时间
		Date beginDate = endDate; //开始时间 
		Date presell_date = null; // 预售日期
		Integer isvalid = 1; // 是否需要开通 
		int vipNum = 1; // 增加的会员天数
		// step 1 从未开通过
		if(userProductService == null) {
			userProductService = new UserProductService();
			
			// step 1.1 
            // 判断是否存在预售日期 这种预售活动只有在上新卡的时候才会有 后期就不会再有的了 所以这里只是需要在第一次开通的时候做判断就行的了
			// 后面的续费以及再次开通的时候就不需要再次管了
            try {
            	// 活动日期截止时间
            	presell_date = productServiceDetail.getPdDateline() == null ? new Date():productServiceDetail.getPdDateline();
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            // step 1.2 
            // 获取购买包月卡赠送天数 前提条件是开通日期在预售日期之前 就是还未到预售截止日期
            if (!presell_date.before(DateUtils.getDateShort(new Date()))) {
                vipNum = vipNum + productServiceDetail.getPdFreeday();
                isvalid = UserProductServiceConstants.ISNOTVALID; // 未到开通时间 
            }
            
            // step 1.4  计算结束时间
            endDate = getVipEndDate(productServiceDetail, endDate, vipNum);
            
            // step 1.6 用户服务信息
            userProductService.setBeginDate(beginDate);
        	userProductService.setEndDate(endDate);
        	userProductService.setIsvaild(isvalid);
        	userProductService.setProductServiceType(productService.getPServiceType());
        	userProductService.setUserId(orderInfo.getUserId());
        	
		}else {
			// stpe 2 已开通过
			// stpe 2.1 续费
			if(userProductService.getIsvalid() == UserProductServiceConstants.ISVALID) {
				
				vipNum = 0;
				beginDate = userProductService.getEndDate();
				endDate = getVipEndDate(productServiceDetail, beginDate, vipNum);
	        	userProductService.setEndDate(endDate);
	        	
			}else if(userProductService.getIsvalid() == UserProductServiceConstants.ISNOTVALID 
					&& userProductService.getBeginDate().compareTo(new Date()) > 0){
				// stpe 2.2 已拥有产品服务但是未到开通时间
				vipNum = 0;
				beginDate = userProductService.getEndDate();
				endDate = getVipEndDate(productServiceDetail, beginDate, vipNum);
	        	userProductService.setEndDate(endDate);
	        	userProductService.setIsvaild(isvalid);
				
			}else {
				// stpe 2.3 重新开通
				beginDate = DateUtils.getDateShort(new Date());
				endDate = getVipEndDate(productServiceDetail, beginDate, vipNum);
				userProductService.setBeginDate(beginDate);
				userProductService.setEndDate(endDate);
				userProductService.setIsvaild(isvalid);
			}
		}
		
		// stpe 3 不存在就新增
        if(userProductService.getId() == null){
        	userProductService.setCreatedBy(orderInfo.getUserId());
        	userProductService.setCreatedTime(new Date());
        	userProductServiceMapper.insert(userProductService);
        }else{
        	// 更新
        	userProductService.setUpdatedTime(new Date());
        	userProductService.setUpdatedBy(orderInfo.getUserId());
        	userProductServiceMapper.updateSelectiveById(userProductService);
        }
        // 创建日志记录的新方法
        createVipPurchaseLogNew(orderInfo, orderInfoResultModel, endDate, beginDate);
        // stpe 4 发生模板消息
        if(sendMsg)
        	templateSendService.sendOpenVIPSuccTemplateMsgNew(orderInfo.getId(), beginDate, endDate,vipNum);
        
	}
	
	/**
	 * 获取 包月卡 结束日期 
	 * @param productServiceDetail
	 * @param endDate
	 * @param num
	 * @return
	 */
	public Date getVipEndDate(ProductServiceDetail productServiceDetail, Date endDate, int num) {
		Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(endDate);
        rightNow.add(Calendar.MONTH, Integer.valueOf(productServiceDetail.getPdType()));// 日期加1个月
        rightNow.add(Calendar.DATE, num);
        return rightNow.getTime();
	}
	
	/**
	 * 创建包月卡充值记录  
	 * @param orderInfo
	 * @param orderInfoResultModel
	 * @param //purchaseType
	 * @param endTime
	 * @param startTime
	 */
	public void createVipPurchaseLogNew(OrderInfo orderInfo, OrderInfoResultModel  orderInfoResultModel, Date endTime, Date startTime) {
		logger.info("============= createVipPurchaseLog start ================================");
		VipPurchaseLog memberPurchaseLog = new VipPurchaseLog();
		Integer purchaseType = OrderContants.PAY_TYPE_WECHAT;
		
		if (orderInfo.getPayType() == OrderContants.PAY_TYPE_PERSON_ACCOUNT) {
            purchaseType = OrderContants.PAY_TYPE_PERSON_ACCOUNT;
        // 企业储值卡方式充值 blank
        } else if(orderInfo.getPayType() == OrderContants.PAY_TYPE_COMPANY_ACCOUNT) {
            purchaseType = 4;// 这里设置为4 因为 3 是檬会员体验卷 这里写死是做了特殊处理
        } else {
            purchaseType = OrderContants.PAY_TYPE_WECHAT;
        }
		
		memberPurchaseLog.setOrderId(orderInfo.getId());
        memberPurchaseLog.setUserId(orderInfo.getUserId());
        memberPurchaseLog.setLevel(orderInfoResultModel.getUserInfo().getLevel());
        memberPurchaseLog.setProductServiceId(orderInfo.getServiceId());
        memberPurchaseLog.setCreatedBy(orderInfo.getUserId());
        memberPurchaseLog.setCreatedTime(new Date());
        memberPurchaseLog.setPurchaseType(purchaseType);
        memberPurchaseLog.setEndTime(endTime);
        memberPurchaseLog.setStartTime(startTime);
        
        int molCount = vipPurchaseLogMapper.insert(memberPurchaseLog);
        logger.info("============= createVipPurchaseLog end : add count  is  "+molCount);
        
	}
	
	/**
	 * 添加用户餐券数量 
	 * @param orderInfoResultModel
	 */
	public void addUserMealCoupon(OrderInfoResultModel orderInfoResultModel) {
		UserMealCoupon userMealCoupon = userMealCouponMapper.queryUserMealCouponByUserId(orderInfoResultModel.getUserId());
		Integer userHasMealCount = 0;
		// 不存在 插入数据
		if(userMealCoupon == null) {
			userMealCoupon = new UserMealCoupon();
			userHasMealCount = orderInfoResultModel.getOrderDetail().getMealCouponCount();
			userMealCoupon.setCreatedBy(orderInfoResultModel.getUserId());
			userMealCoupon.setUserId(orderInfoResultModel.getUserId());
			userMealCoupon.setCreatedTime(new Date());
			userMealCoupon.setVersion(0);
			userMealCoupon.setMealCount(userHasMealCount);
			userMealCouponMapper.insertSelective(userMealCoupon);
			
		}else {
			// 存在 更新数据
			userHasMealCount = userMealCoupon.getMealCount()+orderInfoResultModel.getOrderDetail().getMealCouponCount();
			userMealCoupon.setUpdatedBy(orderInfoResultModel.getUserId());
			userMealCoupon.setUserId(orderInfoResultModel.getUserId());
			userMealCoupon.setUpdatedTime(new Date());
			userMealCoupon.setVersion(userMealCoupon.getVersion()+1);
			userMealCoupon.setMealCount(userHasMealCount);
			userMealCouponMapper.updateSelectiveById(userMealCoupon);
			
		}
		
		
	}
	
	/**
	 * 身份的校验 
	 * @param userId
	 * @param courseInfo
	 * @param orderType
	 * @return
	 */
	public ApiResultModel<Object> checkUserIsHasYearCardService(Integer userId, CourseInfo courseInfo, Integer orderType){
		UserProductService userProductService = userProductServiceMapper.queryUserProductServiceByUserIdAndType(userId, UserProductServiceConstants.SELFTYPESERVICE);
		ApiResultModel apiResultModel = new ApiResultModel<>();
		apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
		// 这里只是校验  团课 私教 檬营 自助 体测 体验 
		if(orderType != OrderContants.OrderType.vip_order.getIndex()
				&& orderType != OrderContants.OrderType.user_account.getIndex()
				&& orderType != OrderContants.OrderType.private_bespeak.getIndex()
				&& orderType != OrderContants.OrderType.monthly_card.getIndex()
				&& orderType != OrderContants.OrderType.mealCoupon.getIndex()) {
			// 没有年卡服务和服务过期的都需要校验
			if(userProductService == null || (userProductService != null && userProductService.getIsvalid() == UserProductServiceConstants.ISNOTVALID)) {
				// 私教课程并且十含有年卡的私教校验是通过的
				if(orderType == OrderContants.OrderType.pt.getIndex() && courseInfo.getProductServiceDetailId() != null && courseInfo.getProductServiceDetailId() == 0) {
					apiResultModel.setRet(apiResultModel.RET_ERROR);
					apiResultModel.setMsg("请先成为会员！");
					return apiResultModel;
				}else if(orderType != OrderContants.OrderType.pt.getIndex()){
					apiResultModel.setRet(apiResultModel.RET_ERROR);
					apiResultModel.setMsg("请先成为会员！");
					return apiResultModel;
				}
				
			}
			
		}
		
		
		return apiResultModel;
	}
   
}
